Print Zero Even Odd - Problem
You have a function printNumber that can be called with an integer parameter and prints it to the console. For example, calling printNumber(7) prints 7 to the console.
You are given an instance of the class ZeroEvenOdd that has three functions: zero, even, and odd. The same instance of ZeroEvenOdd will be passed to three different threads:
- Thread A: calls
zero()that should only output 0's. - Thread B: calls
even()that should only output even numbers. - Thread C: calls
odd()that should only output odd numbers.
Modify the given class to output the series "010203040506..." where the length of the series must be 2n.
Implement the ZeroEvenOdd class:
ZeroEvenOdd(int n)Initializes the object with the numbernthat represents the numbers that should be printed.void zero(printNumber)CallsprintNumberto output one zero.void even(printNumber)CallsprintNumberto output one even number.void odd(printNumber)CallsprintNumberto output one odd number.
Input & Output
Example 1 — Basic Case
$
Input:
n = 2
›
Output:
0102
💡 Note:
Zero thread prints 0, odd thread prints 1, zero thread prints 0, even thread prints 2. Pattern: 0→1→0→2
Example 2 — Larger Sequence
$
Input:
n = 5
›
Output:
0102030405
💡 Note:
Complete sequence: 0→1→0→2→0→3→0→4→0→5. Total length is 2×5=10 characters.
Example 3 — Edge Case
$
Input:
n = 1
›
Output:
01
💡 Note:
Minimum case: zero prints 0, odd prints 1. Length is 2×1=2.
Constraints
- 1 ≤ n ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
n=3, need sequence of length 2×3=6
2
Thread Coordination
Zero→Odd→Zero→Even→Zero→Odd pattern
3
Output
Result: "010203"
Key Takeaway
🎯 Key Insight: Use semaphores to coordinate threads without busy waiting, ensuring perfect alternation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code