Fizz Buzz Multithreaded - Problem
You have four functions: printFizz that prints "fizz", printBuzz that prints "buzz", printFizzBuzz that prints "fizzbuzz", and printNumber that prints a given integer.
You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance will be passed to four different threads:
- Thread A: calls
fizz()that should output "fizz" - Thread B: calls
buzz()that should output "buzz" - Thread C: calls
fizzbuzz()that should output "fizzbuzz" - Thread D: calls
number()that should output integers
Modify the given class to output the series [1, 2, "fizz", 4, "buzz", ...] where the i-th token (1-indexed) is:
- "fizzbuzz" if i is divisible by 3 and 5
- "fizz" if i is divisible by 3 and not 5
- "buzz" if i is divisible by 5 and not 3
- i if i is not divisible by 3 or 5
Input & Output
Example 1 — Basic Case
$
Input:
n = 15
›
Output:
["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizzbuzz"]
💡 Note:
For each number 1 to 15: 1,2 → numbers; 3,6,9,12 → fizz; 5,10 → buzz; 15 → fizzbuzz
Example 2 — Small Range
$
Input:
n = 5
›
Output:
["1", "2", "fizz", "4", "buzz"]
💡 Note:
1,2,4 are regular numbers; 3 is divisible by 3 only → fizz; 5 is divisible by 5 only → buzz
Example 3 — Include FizzBuzz
$
Input:
n = 30
›
Output:
["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizzbuzz", "16", "17", "fizz", "19", "buzz", "fizz", "22", "23", "fizz", "buzz", "26", "fizz", "28", "29", "fizzbuzz"]
💡 Note:
Numbers 15 and 30 are divisible by both 3 and 5, so they become fizzbuzz
Constraints
- 1 ≤ n ≤ 50
Visualization
Tap to expand
Understanding the Visualization
1
Input
n = 15 (generate sequence from 1 to 15)
2
Thread Coordination
Four threads check conditions and execute in order
3
Output
Sequential FizzBuzz sequence with proper synchronization
Key Takeaway
🎯 Key Insight: Thread synchronization ensures correct sequential output despite concurrent execution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code