DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
 
darthbob88 profile image
Raymond Price

First obvious solution is to use nested ternaries to get around the if/else restriction, but the rules also frown on ternaries.

Second option is switch/case on ii % 15, like

for (var ii = 1; ii <= 100; ii++) {
    switch (ii % 15) {
        case 0: console.log("Fizzbuzz"); break;
        case 1: console.log(ii); break;
        case 2: console.log(ii); break;
        case 3: console.log("Fizz"); break;
        case 4: console.log(ii); break;
        case 5: console.log("Buzz"); break;
        case 6: console.log("Fizz"); break;
        case 7: console.log(ii); break;
        case 8: console.log(ii); break;
        case 9: console.log("Fizz"); break;
        case 10: console.log("Buzz"); break;
        case 11: console.log(ii); break;
        case 12: console.log("Fizz"); break;
        case 13: console.log(ii); break;
        case 14: console.log(ii); break;
    }
}
Enter fullscreen mode Exit fullscreen mode

I believe you can also do this with an array, console.log(options[ii%15]), but I don't care enough to test that would actually work for JS.

Another option I've seen and liked is seeding the RNG with the correct value and using the outputs from that to index an array of options to print, something like srand(MAGIC); for (var ii = 1; ii <= 100; ii++) print ["Fizz", "Buzz", "Fizzbuzz", ii][rand.next() % 4]; } But that definitely doesn't work in JS, since you can't seed the RNG.