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 number n that represents the numbers that should be printed.
  • void zero(printNumber) Calls printNumber to output one zero.
  • void even(printNumber) Calls printNumber to output one even number.
  • void odd(printNumber) Calls printNumber to 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
Print Zero Even Odd: Thread CoordinationInput: n = 3, Expected Output: "010203"010203ZeroOddZeroEvenZeroOddThread Azero()Prints: 0Thread Beven()Prints: 2Thread Codd()Prints: 1, 3Final Output: "010203"Length = 2n = 6 characters
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
Asked in
Google 25 Microsoft 20 Amazon 15 Facebook 12
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen