67.2k views
4 votes
Reimplement the Traffic Light class using a simple counter that is advanced in each call to next. If the traffic light was initially green, the counter has values 0123456. If the traffic light was initially red, the counter has values 2 3 4 5 6 7 8.... Compute the current color and the number of reds, using integer division and remainder.​

1 Answer

7 votes

Answer: The current color is green, and the number of reds is 2.

Explanation: This solution assumes that we start with a green light.

If the traffic light was initially green, the counter has values 0123456. If the traffic light was initially red, the counter has values 2 3 4 5 6 7 8…

To compute the current color and the number of reds, we can use integer division and remainder. Let’s assume that we start with a green light. We can define a counter that starts at 0 and increments by 1 each time we call the next method. We can then compute the current color and the number of reds as follows:

counter = 0

num_reds = counter // 3

current_color = 'green' if num_reds % 2 == 0 else 'red'

Here, // is the integer division operator and % is the remainder operator. The expression counter // 3 gives us the number of times we have advanced the counter since the last red light. The expression num_reds % 2 == 0 checks whether we are currently in a green or red phase.

For example, if we call next six times, we get:

counter = 6

num_reds = counter // 3 = 2

current_color = 'red' (since num_reds % 2 == 0 is False)

So the current color is red and there have been two red phases so far.

Hope this helps, and have a great day!

User Questiondude
by
8.1k points