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 - Semaphore Synchronization INPUT n = 2 Three Threads: Thread A zero() Thread B even() Thread C odd() Semaphores: zeroSem=1 oddSem=0 evenSem=0 Expected: Series of 2n digits "0102" (length=4) ALGORITHM STEPS 1 Initialize Semaphores zeroSem=1, oddSem=0, evenSem=0 2 zero() prints 0 Acquire zeroSem, print 0, release odd/even based on i 3 odd() prints odd nums Acquire oddSem, print num, release zeroSem 4 even() prints even nums Acquire evenSem, print num, release zeroSem Execution Order: 0 1 0 2 -- -- -- FINAL RESULT Output Sequence: 0 1 0 2 "0102" Verification: Length = 4 = 2 x n [OK] Pattern: 0,odd,0,even [OK] Sync: Correct order [OK] SUCCESS Key Insight: Semaphores act as gates controlling thread execution order. The zero() thread always runs first (zeroSem starts at 1), then alternates between signaling odd or even threads. Each odd/even thread signals back to zero after printing, creating the synchronized "010203..." pattern. TutorialsPoint - Print Zero Even Odd | Semaphore-Based Synchronization
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