Model a traffic light whose transitions are stored as a Map from state to UnaryOperator, with timing per state; simulate the light for 100 seconds and print each change.
Solution
Main.java
import java.util.EnumMap;
import java.util.Map;
import java.util.function.UnaryOperator;
enum Light { GREEN, YELLOW, RED }
public class Main {
public static void main(String[] args) {
Map<Light, UnaryOperator<Light>> next = new EnumMap<>(Light.class);
next.put(Light.GREEN, l -> Light.YELLOW);
next.put(Light.YELLOW, l -> Light.RED);
next.put(Light.RED, l -> Light.GREEN);
Map<Light, Integer> seconds = new EnumMap<>(Map.of(Light.GREEN, 30, Light.YELLOW, 5, Light.RED, 25));
Light state = Light.RED;
int t = 0;
while (t < 100) {
System.out.printf("t=%3d %s for %ds%n", t, state, seconds.get(state));
t += seconds.get(state);
state = next.get(state).apply(state);
}
}
}
Output Verified by compiling and running
t= 0 RED for 25s
t= 25 GREEN for 30s
t= 55 YELLOW for 5s
t= 60 RED for 25s
t= 85 GREEN for 30s
Transitions are data (lambdas in a map), so changing the sequence means changing the map, not the loop.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!