Question Bank
JavaScript FizzBuzz: Two Implementations Quiz
Difficulty: Medium
Two seeded FizzBuzz implementations (modulo branching and order-sensitive variant) plus two companion drills covering a generalized N-divisors version and a micro-benchmark.
JavaScript FizzBuzz: Two Implementations Quiz
Two seeded FizzBuzz implementations (modulo branching and order-sensitive variant) plus two companion drills covering a generalized N-divisors version and a micro-benchmark.
231 views
5
Implement classic FizzBuzz from 1 to n: print fizz for multiples of 3, buzz for multiples of 5, fizzbuzz for multiples of both, otherwise the number. Solve it with explicit modulo branching and the most-specific case first.
Examples
Example 1:
Input: 5
Output: 1, 2, fizz, 4, buzz
Explanation: 3 hits the fizz branch, 5 hits the buzz branch; the rest print as numbers.Example 2:
Input: 15
Output: ..., fizz, 13, 14, fizzbuzz
Explanation: 15 must print `fizzbuzz` because it is divisible by BOTH 3 and 5; that branch has to come first.Implement FizzBuzz from 1 to n using mutually-exclusive branches: each if excludes the other divisor explicitly (so a 3-only branch fires only when not divisible by 5). Explain why branch order matters less in this variant than in the combined-check style.
Examples
Example 1:
Input: 6
Output: 1, 2, fizz, 4, buzz, fizz
Explanation: At i=6 the (3 yes, 5 no) branch fires; at i=5 the (5 yes, 3 no) branch fires.Generalize FizzBuzz to N divisors. Implement genericFizzBuzz(n, rules) where rules is an array of { divisor, word } and the function concatenates every matching word per number (falling back to the number itself when nothing matches).
Examples
Example 1:
Input: n = 15, rules = [{divisor: 3, word: 'fizz'}, {divisor: 5, word: 'buzz'}]
Output: ..., fizz, 13, 14, fizzbuzz
Explanation: 15 collects 'fizz' AND 'buzz' from the two matching rules, then concatenates.Example 2:
Input: n = 7, rules = [{divisor: 2, word: 'pop'}, {divisor: 3, word: 'tart'}, {divisor: 7, word: 'cake'}]
Output: 1, pop, tart, pop, 5, poptart, cake
Explanation: At i=6 both 2 and 3 match, producing 'poptart'; at i=7 only the cake rule matches.Performance: on n = 1_000_000, which is faster, a per-iteration modulo-branching FizzBuzz that calls console.log inside the loop, or a string-builder version that pushes each line into an array and calls console.log(arr.join('\n')) once at the end? Justify with a micro-benchmark.
Examples
Example 1:
Input: n = 1_000_000, two implementations
Output: array-builder is usually faster than per-iteration console.log
Explanation: Console I/O dominates wall-clock; batching into a single console.log at the end avoids the per-call overhead.