DEV Community

Discussion on: Get Your (Fizz)Buzz On

Collapse
 
stanleynguyen profile image
Stanley Nguyen

Another one of the scalability aspects that we can explore is that what if the game wont stop at just 2 denominators (e.g. If I add 7 to the game, so for numbers multiple of 3 print Fizz, multiple of 5 print Buzz, multiple of 15 (3 and 5) print FizzBuzz, multiple of 35 (5 and 7) print BuzzBazz, multiple of 21 (3 and 7) print FizzBazz, and multiple of 105 (3 and 5 and 7) print FizzBuzzBazz). How we would go about scale it up on this aspect is to make use of hashmap, iterating through the map to determine the output. Here is the implementation in Go:

package main

import (
    "fmt"
    "sort"
    "strconv"
)

func scalableFizzBuzz(num int, denominatorsMap map[int]string) {
    // make a list of keys and sort it in order from small -> large
    // this is to make sure that it prints out "FizzBuzzBazz"
    // instead of random order like "BuzzFizzBazz" due to the
    // random nature of map iterator
    keys := make([]int, 0)
    for k := range denominatorsMap {
        keys = append(keys, k)
    }
    sort.Ints(keys)

    for i := 1; i <= num; i++ {
        output := ""
        for _, k := range keys {
            if i%k == 0 {
                output += denominatorsMap[k]
            }
        }
        if output == "" {
            output += strconv.Itoa(i)
        }
        output += ", "
        fmt.Print(output)
    }
}

func main() {
    scalableFizzBuzz(300, map[int]string{3: "Fizz", 5: "Buzz", 7: "Bazz"})
}
Collapse
 
stanleynguyen profile image
Stanley Nguyen

Here is the solution in js

function scalableFizzBuzz(num, denominatorsMap) {
  for (let i = 1; i <= num; i++) {
    output = "";
    Object.keys(denominatorsMap).forEach((k) => {
      if (i%k === 0) {
        output += denominatorsMap[k];
      }
    });
    if (output === "") {
      output += i;
    }
    console.log(output);
  }
}

scalableFizzBuzz(300, { 3: "Fizz", 5: "Buzz", 7: "Bazz" });
Collapse
 
yechielk profile image
Yechiel Kalmenson • Edited

Nice, I never thought of scaling it in that direction.

I like the idea of using a Hash.