Hope you’re all familiar with this problem, but if not, you can read this article for context and try it yourself on LeetCode (it’s an easy-level problem).
Back in February, I created a repository called fizz-buzz-world, making it easy for others to contribute. I added a few of my own solutions, basic logic tests, and a well-organized README encouraging people to submit their own versions of this classic problem.
The goal was simple: gather creative, out-of-the-box Fizz Buzz solutions written in Go.
Solving It Without Ifs
For example, here are a couple of my solutions that avoid using a single if:
|
|
And here’s another one:
|
|
Obviously, during an interview, it’s better to stick to the classic solution, so you don’t confuse your interviewer (since they’ll have to check it).
The Lucky Number
Last week, the fizz-buzz-world repo received a fascinating new solution.
Big thanks to the author: pull request was very well-crafted and documented. The proposed solution is incredibly non-obvious and really interesting. You can read more in his README.
The core idea is based on a “lucky number” (not to be confused with the number from number theory), which is calculated specifically for this task. In Go 1.23.2, the lucky number is: 176064004
Knowing this, the solution looks like this:
|
|
Unpacking the Magic
To implement this, the first thing we need is the ability to create a random number generator.
This is where the concept of a random seed comes in—it’s a number that ensures a generator will always produce the same pseudo-random sequence.
In Go, we have the rand.NewSource function, which allows us to set the “seed”—in our case, this will be our “lucky number.”
The main challenge becomes finding that number. You can check the full implementation here, but let’s walk through one function to get the core idea:
|
|
“yep” is an array that contains the correct indexes for the first 15 iterations. If you take the string from the list of possible answers: {””, Fizz, Buzz, FizzBuzz}, you’ll get the correct value at each step:
|
|
So, we need to find a number that will “randomly” generate the correct answer for the first 15 elements.
Once you’ve found the right number, all that’s left is to generate this sequence and then repeat it. By reinitializing the randomizer with the same seed every 15 iterations (“if i%15 == 1”), you’ll duplicate the sequence as many times as you need:
|
|
This is an unusual approach to solving the problem. It might look like a bit of a hack, but it gets you the correct answer in a pretty clever way.
Share Your Solution
Got more creative ideas for solving Fizz Buzz? Feel free to contribute.
Don’t know Go but familiar with the original method in other languages? Create an issue, and we’ll translate your solution into Go! Let’s collect the craziest Fizz Buzz solutions together ;)
Read the original post and join the discussion in Telegram: @time2code