‹ back to the board

Tuesday, September 1

Mastermulti-constraint & composite logic

The Sexton's Hour-Ledger

The sexton of bitwick keeps the tower's work in shorthand, and no two masons write it the same way. Before the ledger goes up to the guild it has to be rewritten in the single form the guild accepts.

Write tidyLedger(expr), which takes a string and returns a string.

The shorthand. expr is one whole entry. It is well-formed only if all of these hold:

  • it is not the empty string;
  • it is one or more *marks* separated by exactly one space each, with no leading or trailing space;
  • a mark is an optional -, then an optional count in decimal digits, then exactly one unit letter from f, w, d, h, m;
  • a count, if it is present, has no leading zero unless it is exactly 0.

A missing count means 1, so h is one hour and -h is minus one hour.

The units are worth, in minutes: m 1, h 60, d 480 (eight hours), w 2400 (five days), f 4800 (two weeks). Marks may repeat units and may come in any order. The value of the entry is the sum of its marks.

What to return. If expr is not well-formed, return the empty string.

Otherwise return the guild form of the entry's value:

  • if the value is zero, return "0m";
  • otherwise take the magnitude of the value in minutes and split it into weeks, days, hours and minutes, taking as many weeks as possible, then as many days as possible, then as many hours as possible, with whatever remains as minutes. The guild form never uses f. Write the parts whose count is not zero, in the order weeks, days, hours, minutes, separated by single spaces, each written as the count followed by its unit letter, and each prefixed with - if the value is negative.
  • format round-tripping
  • Master

examples

  1. case 1expr of "3d 25h 90m""1w 1d 2h 30m" - the entry is 1440 + 1500 + 90 = 3030 minutes, which is one week, one day, two hours and thirty minutes
  2. case 2expr of "f -w""1w" - a fortnight less a week is 2400 minutes, and the guild form never writes f
  3. case 3expr of "1h -90m""-30m" - the value is thirty minutes below zero
  4. case 4expr of "2h 03m""" - the count 03 has a leading zero, so the entry is not well-formed
reward
540 XP
signature
tidyLedger
not yet run

TypeScript, run as ES2022 — types are stripped, not checked. If a JS engine would run it, so will we.

loading the editor…
  • carries up through weeks
  • fortnight folds into weeks
  • implicit count of one, negated
  • negative total signs every part
  • marks cancel exactly
  • mixed signs fall below zero
  • empty entry is not well-formed
  • leading zero rejected
  • double space rejected
  • leading space rejected
  • two unit letters in one mark rejected
  • unknown unit rejected
  • bare minus with no unit rejected
  • five days make a week exactly
  • hundred hours split three ways
  • ten fortnights
  • already in guild form
The Sexton's Hour-Ledger · bitwick