Friday, 25 March 2022

FizzBuzz, my arse

If you ever look me up on Goodreads, you'll find that I took an age to read The Fizz Buzz Fix: Secrets to Thinking Like an Experienced Software Developer.. I was primarily interested in reading about the FizzBuzz problem and found the rest exhausting (I wonder if they do it as an audio version?). Anyway, I found myself pondering it again recently and came across this version by Brandon Morelli:

for(let i=0;i<100;)console.log((++i%3?'':'fizz')+(i%5?'':'buzz')||i)

Aye, it's brilliant, but all approaches seem to end up using a For loop, and I got to thinking about alternatives. Thanks to messing about with other coding challenges, I clocked the way of generating an array, then thought about using that generated array with a forEach:

Array.from({length: 100}, (_, i) => i + 1).forEach(i => { 
  console.log((i%3 && i%5) ? `${i}` : `${i} ${(i%3 ? '' : 'Fizz') + (i%5 ? '' : 'Buzz')}`) 

This method has the benefit of not adding an extra space after the number for those numbers that aren't divisible by three or five. The forEach seems as fast for numbers up to 100 during testing and faster for numbers up to 1000.

The images of code are from, bloody brilliant aren't they?

No comments:

Post a Comment