Starting up...

FizzBuzz without multiplication or division, part 2

This is the second of a three-part series: Part 1, Part 3.

Last time on Lost In Permutation, I wrote a FizzBuzz implementation that didn't use the run-time multiplication and division operators. Unfortunately, magic numbers make me squeamish, and there is too much coupling between the data in rg and the if-chain. In order to change the behavior of the function, I would have to change both places.

To fix this, I can use printf() (which doesn't care if I pass an extra parameter) as the dispatcher. The more decisions I can foist onto the runtime, the less code I have written, which is great because it means I have less code to test, less code to read, and less code to maintain.

void FizzBuzz(int n) {
  char* num = "%d\n";
  char* fizz = "Fizz\n";
  char* buzz = "Buzz\n";
  char* fizzbuzz = "FizzBuzz\n";
  
  char* rg[15] = { fizzbuzz, num, num, fizz, num, buzz, fizz, num, num, fizz, buzz, num, fizz, num, num };
  int ix = 1;
  
  for(int i=1; i<=n; i++)
  {
     printf(rg[ix], i);
     
     ix++;
     if(ix==15) ix = 0;
  }
}

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

- Antoine de Saint-Exupéry

Now there is no longer an if-chain that needs to be tested, only the prepopulated data in the ring buffer rg and the behavior of the ring buffer itself. Except for the magic constant 15, the only place to make changes to the function is in rg itself. When this series concludes, I will examine how to expand this printf-dispatch solution for any variant of the FizzBuzz problem.

GitHub Stack Overflow LinkedIn YouTube