Stopwatch in Ticks
Implement a class Stopwatch that measures time in whole ticks. The methods that take now receive the current time, and now never decreases from one call to the next. Write these methods:
Stopwatch()makes a stopwatch that is stopped and shows0ticks.press_start(now)starts the stopwatch at timenowand returnstrue. If it is already running, nothing changes and it returnsfalse.press_stop(now)stops the stopwatch and returns the length of the run that just ended:nowminus the time it was started. If the stopwatch is not running, nothing changes and it returns-1.read_ticks(now)returns the total length of all finished runs, plus the current run up tonowif the stopwatch is running.clear()stops the stopwatch if it is running and sets the total back to0. It returns nothing.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor and for clear.
Example 1
Stopwatch()
press_start(2) returns true
read_ticks(5) returns 3
press_stop(9) returns 7
press_start(9) returns true
press_start(10) returns false
read_ticks(12) returns 10
press_stop(15) returns 6
read_ticks(20) returns 13
The first run lasts from 2 to 9, so 7 ticks; at time 5 it had run 3. The second start at 10 is ignored because the watch is running. The second run lasts 6, for a total of 13.
Constraints
0 <= now <= 1000, andnownever decreases from one call to the next- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.