This challenge is intended for Javascript, but you can complete it with any language you like and can.
Most of us will know the FizzBuzz game/exercise and probably have done it many times. It should be a simple and straightforward exercise for most developers...
BUT can you do it without using if/else
statements?
Challenge Description
Write a program that outputs the string representation of numbers from 1 to N.
But for multiples of 3, it should output "Fizz" instead of the number and for the multiples of 5 output "Buzz". For numbers which are multiples of both 3 and 5, you should output "FizzBuzz".
Curveball: You must not use if/else statements, and ideally, no ternary operator.
Example:
const n = 15;
/*
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
*/
I will comment my solution in a couple of days.
πͺ Best of luck! πͺ
Credits:
Cover Image from https://codenewbiesite.wordpress.com/2017/01/29/fizz-buzz/
Discussion (95)
Easy, just do it in CSS.
Needs some Markup to display obviously.
Ha!
This is truly ingenious!
Magnificent! I knew there were going to be really neat solutions!!
Thanks for sharing your solution πͺ
Javascript taking advantage of
||
operator:This is what makes my developer heart jump for joy ππ Awesome, Bryan!
That made my day. Thanks. π
Cool solution! I thought to do something similar at first, but ended up doing some weird stuff!
The cleanest and best FizzBuzz implementation I know of doesn't use any if statements at all. Actually it doesn't use any control flow at all in most languages.
The approach is fully described here: philcrissman.net/posts/eulers-fizz...
On my Repl.it I also have this same approach implemented in several other languages:
repl.it/@rushsteve1/
This was great! Love it when there is a simple probable mathematic solution to these kinds of things!
Me too, so clean! I love maths but I'm crap at it myself xD
I did not know about this, thanks for sharing. I will remember this!
Neat solution, thanks for sharing it!
Is there a reason you use
t.call()
instead of calling the function directlyt()
?Thanks. Yes, haha, the reason is that my head was a bit worn out so late at night π€ͺ. I have another improvement, will post it shortly.
Ohh yup, I know that feeling xD
Here we go. This is a bit more streamlined:
Holy sh*t, my other solution was really ugly! :-o
Here is a (much) better one (also in Python3):
This works using the property that
True
in Python has numerical value1
and using f-strings in an array. The proper element in the array is chosen based on the mentioned property, checking for divisibility with 3 and 5.logical operators
The second half of an "and" statement only evaluates if the first half is true.
...
for loops
For loops check your second declaration on each iteration. Force it to be false on the second iteration, and you've got something that'll check your condition a single time.
...
arrays
Referencing an index that that exists gives you the value stored there, but referencing an index that doesn't exist gives you undefined. Use an "or" statement to give yourself a fallback value when this happens, and you'll be ready to go.
Or, fill an array with your options, and leverage the fact that true can be used as 1 in JavaScript to do some index-selection math.
...
try/catch blocks
You can purposefully throw exceptions when a boolean is false by referencing a variable that doesn't exist (the "throwException" variable in this case).
...
while loops
This is the same concept as for loops. Force the loop to stop after one iteration (this time with a break), and you've got something that'll check your condition a single time.
...
switch statements
Who could forget the classic alternative to if statements? Technically not even cheating!
Wow, those are some solutions right there! Thanks a lot for sharing and taking the time to explain it.
I did some silly stuff, just for fun lol:
You can still have flow control with functions.
I liked this approach! Thanks for sharing!
Here's the simplest I can think of without any statements. π
Nice, recursion for the win πͺ
Thanks for sharing!
Here is an ugly solution in one line
U aren't supposed to use Ternary Operator.
Oh yeah! didn't notice that, I have updated my solution
I do feel like this was kinda cheap...
I like it!
Nice stuff! Cool use of a generator. And yeah kinda cheap but cool nonetheless, thanks for sharing!
Some improvement to my earlier version.
A) better (arguably, because way more cognitive load than the very simple one above)
B) above one as 1 liner b/c hello perl
Also thinking about overriding Number.prototype.toString makes a fun thingy. Maybe someone already did, but someone for sure should :D
There was a similar and equally really good thread about a month ago that had some devilishly clever solutions... highly recommend it!
My contributions below:
Nice stuff. I will be checking out the thread!
There have been some really clever solutions posted here as well.
Here is some python for you :)
Manolo Edge
@nombrekeff
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
, likeI 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.There's a lack of pattern matching and recursion in the comments, so here we go:
Nice, thanks for sharing this approach.
Rickard Laurin just posted another similar approach in ReasonML as well.
My solution in Rust:
Clojure example.
I quite like Andrew's bit shift array example. Only think that its better to have a
nil
zeroth value so you get circuit breaking for free.repl.it link
A solution in Python. Feels silly though...
Wait until you see mine π
Here's my initial cut at a Python solution:
This just cycles through the array and prints the appropriate response, though I've already seen more clever ways to do it.
Here's a solution to the challenge in JavaScript...
Here's a repl.it where you can run this.
Here you have in Python
Came up with 2 in Kotlin. Both could definitely be improved, but this was a fun exercise in thinking about control flow!
I did something similar to your fizzbuzz in C# 8.0:
Really nice idea!
Here's how I did it π
Glad you liked it!
I just published a new challenge if you want another one :)
[Challenge] log("this") or log("this").withData({})
Manolo Edge γ» Aug 19 γ» 1 min read
One of the ways in Clojure:
Original idea seen here: clojuredocs.org/clojure.core/cond-...
Here's a solution I like very much, because it uses function composition:
It's heavily inspired by tokdaniel's gist.
Ironically, I have a Python-based solution for this as an example in my upcoming EuroPython 2020 presentation!
I picked up the
*
trick on a StackOverflow answer about this a while back, but I adapted it.Here's an example in ReasonML
Runnable example: sketch.sh/s/XABe2ghxBqncDWTTKpNK8n/
Trick is to map the modulo results into a true/false value. Then use that as a 0 or 1 index into an array of two strings.
C++
And the above can be further reduced to a single array table by exploiting multiplication against a bool expression