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...
For further actions, you may consider blocking this person and/or reporting abuse
Easy, just do it in CSS.
Needs some Markup to display obviously.
Ha!
Magnificent! I knew there were going to be really neat solutions!!
Thanks for sharing your solution πͺ
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!
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:
Here's the simplest I can think of without any statements. π
Nice, recursion for the win πͺ
Thanks for sharing!
You can still have flow control with functions.
I liked this approach! 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
Here is some python for you :)
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.
Manolo Edge
@nombrekeff
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
My javascript solution, modeled after my C++ solution and then reduced
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
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
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.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
Here's an example in ReasonML
Runnable example: sketch.sh/s/XABe2ghxBqncDWTTKpNK8n/
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.
Thanks for the fun challenge!
I'm not sure if JavaScript's type conversion is considered cheating, but I thought it was cool and wanted to share!
Hmm... As a bootcamp student, I'm trying to untangle this.
[!(offsetIndex % 3) + 0]
I see this checks the modulus, and inverts the result. Any non-zero int is truthy, and this expression makes it false . . .
+0
to coerce thefalse
to an int. That is enough that the entire thing evaluates falsy, which then results in outputtingoffsetIndex
on the otherside of theor
. I had to drop this in a node repl to follow it, but I eventually got it πBut what is the
["", "Fizz"][!(offsetIndex % 3) + 0]
double-array looking thing there? I thought it was a 2d array at first, but that doesn't seem right for a number of reasons.I'm pretty sure the first pair of square brackets creates an array, and the second one indexes into that array. So I think they are array indexing into the first array with either 0 or 1 to pick the empty string or "Fizz" depending on the offsetIndex!
Hope that helps!
yup, it defines the array first
const array = ["", "Fizz"]
and then access the indexarray[!(offsetIndex % 3) + 0]
. The expression will resolve either totrue+0 -> 1
orfalse+0 -> 0
holy shit. that's cool.
I THOUGHT it might have been something like that, but I was thinking about it wrongly . . . I wasn't thinking of it as the array followed by the index, I was thinking of it as a variable. So
["an", "array"]
was the name of the array, and then it had it's own index. Not very practical.But the actual use is quite cool and makes plenty sense.
Thanks!
why
_value
?I understand that the 'convention' for
_
is for private, but is there some other use for it here?Or is it just habit π
It is also a convention for unused parameters.
Thanks for sharing Jesse!! It's a really neat solution π€!
Also not cheating at all!
A solution in Python. Feels silly though...
Wait until you see mine π
My approach is to take advantage of string replace π€£οΈ
Smart!
Yet another Python solution using dict and except instead of if / else. I think i'ts valid and quite readable :p
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:
py3, oneliner because ofc
If it were up to me, I'd declare this the winner.
working with arrays (indexes), no for loop because it's conditional too,
if fizz it will give index 1, if buzz 2, if fizz and buzz 1 + 2 => 3 FizzBuzz (Anything else will give 0 and go to real number cause we put words[0] = num)
that's it :)
Very stupid solution ! but this is the first thing that comes to my mind !
fun challenge! this is the simplest thing I can think of at the moment
Here is my solution, I came up with a couple of solutions, but I will share this one as nobody has posted it. It's not the best approach, though. It's quite silly:
Neat solution, thanks for sharing it!
Is there a reason you use
t.call()
instead of calling the function directlyt()
?Cool solution! I thought to do something similar at first, but ended up doing some weird stuff!
Thanks for the fun challenge! My solution uses bitwise operators and objects to get the answer:
Neat!
An alternative using recursion instead of native methods.
I did that in scheme r5rs:
As promised, no ifs.
Thanks for sharing Tanguy!
Cool stuff! Haven't heard about r5rs, looks complicated, but cool :P
Oh it isnβt that hard, it might seem complicated because of all the parenthesis and strange keywords like cons, but itβs actually just a matter of getting used to it. Itβs a fun language to learn recursion for example.
It becomes a lot simpler when you learn the patterns for building recursive functions, at one point, you donβt even look at the whole function because you just think of the parts.
I started by making a function that looks like that:
This function just returns the list of numbers from 1 to 15, that's what it does because the
compute
function just returns whatever isn
. Then I simply filledcompute
with my conditions.define
is used to define variables and functions,cons
is used to build a list from a head and a queue (that's not hard to understand but it definetely requires some practice and research,let*
allows to define local variablesWhat a legend! I wasn't expecting an explanation, but it's highly appreciated!
Looks interesting, and after your explanation, it does not look as complicated, I might give it a try somedayπͺ
And yeah, most languages seem a bit overwhelming at first.
Thanks! Feel free to ping me for help if you try to get into it and feel stuck.
Thank you! I will if I get into it :)
I don't know this language, but the
(and (zero? ...
sounds like ternaries to me :)Itβs not a ternary, itβs just like doing && in other languages. Now you can emulate a ternary with it, I think that was the goal of the challenge. No ifs and no ternary.
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!
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.Here you have in Python
Pretty interesting cheers! I recall using it on the CLI at some point, but without actually knowing it was a language!
A bit late to the party but here is my take. I'm basically substituting
cond ? valueWhenTrue : valueWhenFalse
for a logical equivalent(cond && valueWhenTrue) || valueWhenFalse
+ calling the function recursively.Note: array returned is in reverse order ! But we can easily solve that with
.reverse()
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:
Nice, I have heard about it but never saw any writen code for awk!!
That's pretty neat! It reminds my a bit of rust's match. What was/is awk usually used for?
Bit late to the party...
Maybe we could have it ready from the DB. I know CASE / WHEN / THEM is sql if / else equivalent, but nobody tried yet, so here he go
Here's my proposal for a non if/else implementation
Using only Types and Abstractions (Interface) and a bit a Linq (C#)
But the most important part is using full polymorphism and a DDD style with immutable objects (structs)
Made with strict TDD (all tests green), please check my repo
My 10 cents:
you should have said: FizzBuzz with a Cyclomatic Complexity to maximum 2 (or 1).
Because if you replace a if/else by Logical Operators, or Switch or While or For, you aren't doing better code in terms of Cyclomatic Complexity
The CSS approach is one of the most elegant.
Another one without any cyclomatic complexity is acheived with a strong type system, like what you can do in Haskell, F#; Kotlin or TypeScript
See that solution (not mine, but clever if you understand the type inference mecanism) gist.github.com/na-o-ys/34e9ebf7fc...
Ohh yup, I know that feeling xD
What about using ternaries?
Ideally not, but feel free to use them! There are many solutions without using them though ;)
What about switch cases???? Can we use it?
Sure, switch is allowed!