Traffic Light State Machine with Enum
Problem
A traffic light starts at RED. The order of the states is RED, GREEN, YELLOW, then RED again. Read n, the number of changes, and print the state after n changes.
Constraints
- 0 <= n <= 10^12
Examples
Input
4
Output
GREEN
Solutions
An enum limits a value to a fixed set. The cycle repeats every 3 changes, so n % 3 is enough even for a very large n. TypeScript enums are not used here because they need a compiler step; a frozen object is a safe equal.
/*
* Problem : Traffic light.
* Input : One integer n.
* Output : The state name.
* Approach: Enum with next().
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: An enum is a fixed list of allowed values. Each value knows the next one.
enum Light {
RED, GREEN, YELLOW;
Light next() {
return values()[(ordinal() + 1) % values().length];
}
}
// This method solves the task. It receives the input and returns the answer.
static String solve(long n) {
// Step 2: Start at RED and move to the next state. Only n % 3 changes matter, because the cycle has 3 states.
Light light = Light.RED;
for (long i = 0; i < n % 3; i++) {
light = light.next();
}
return light.name();
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (1)
- How many changes bring the light back to RED?