Traffic Light on a Timer
Implement a class TrafficLight that shows green, then yellow, then red, then green again, forever. Write these methods:
TrafficLight(green, yellow, red)gives how many seconds each color lasts. At time0the light has just turned green.wait(t)letstseconds pass and returns the color now:"green","yellow"or"red".read_color()returns the color now.get_seconds_left()returns how many seconds are left until the color changes.count_changes()returns how many times the color has changed since time0.
At the exact moment the time of a color runs out, the light shows the next color: with green = 5 it shows yellow at time 5. The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
TrafficLight(5, 2, 3)
read_color() returns "green"
wait(5) returns "yellow"
get_seconds_left() returns 2
wait(4) returns "red"
wait(7) returns "yellow"
count_changes() returns 4
At time 5 green has just run out, so the light is yellow with 2 seconds left. By time 16 the light has gone from green to yellow, yellow to red, red to green and green to yellow again: 4 changes.
Constraints
1 <= green, yellow, red <= 600 <= t <= 500- 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.