Car Trialling
Time limit1sMemory limit128 MB
Parse each line against a small case-sensitive grammar and decide whether it is a valid car-trialling instruction, echoing it with spaced collapsed or printing Trap!.
- Level
Medium6 of 10
- Topics
- String, Implementation, Recursion, Brute force
- Solved
- No attempts yet
Problem
Car trialling is a motorsport in which the driver must follow a set of very precisely worded instructions. When designing a trial, the organiser deliberately plants "traps" in the wording to catch out the unwary.
Write a program that decides whether an instruction obeys the rules below, which are loosely based on real car-trialling instructions.
The grammar uses the following notation:
- Words in UPPERCASE (for example
GO,KEEP,RIGHT) are literal text that must appear exactly as shown; matching is case sensitive. - Lowercase names are grammar rules.
|separates alternatives, exactly one of which must be chosen...expands a range, soA..DmeansA | B | C | D.
instruction = navigational | time-keeping | navigational AND time-keeping
navigational = directional | navigational AND THEN directional
directional = how direction | how direction where
how = GO | GO when | KEEP
direction = RIGHT | LEFT
when = FIRST | SECOND | THIRD
where = AT sign
sign = "signwords"
signwords = s-word | signwords s-word
s-word = letter | s-word letter
letter = A..Z | .
time-keeping = record | change
record = RECORD TIME
change = cas TO nnn KMH
cas = CHANGE AVERAGE SPEED | CAS
nnn = digit | nnn digit
digit = 0..9
s-word and nnn are sequences of letters and digits respectively, with no spaces inside them. Consecutive items are separated by one or more spaces, with three exceptions where there is no space at all: immediately before a period (.), immediately after an opening quotation mark ("), and immediately before a closing quotation mark (").
Input
The input consists of several instructions, one per line. Each line contains at most 75 characters. The input ends with a line containing a single #, which is not itself an instruction and must not be processed.
Output
For each instruction line, print one numbered line. Lines are numbered sequentially starting from 1.
Each output line starts with the line number, right-justified in a field of 3 characters, followed by a full stop (.) and a single space. After that:
- if the instruction is valid, print the instruction itself, with every run of more than one space reduced to a single space;
- otherwise, print
Trap!.