Fastest? We need benchmarks to show that. I can see this being slower than traditional approaches on systems with slow memory, tiny CPU caches, and compilers that don’t do constant string folding.
You can also replace the array by a single string. That may or may not be faster, depending on CPU and language implementation. I think it likely is (rationale: the code writing the array to stdout either does multiple write calls, or builds up the string in memory and then does what the code writing the string does. The code writing the array need not load the string, but it needs to store the array, and that won’t be much smaller, even when it shares strings)
It would be more elegant in a lazy language, but it is probably quite fast since it doesn't need any division (?? My assumption here might be wrong). I typed this out on my phone, so it might not work, and racket isn't my daily driver.
Edit: My initial assumption was correct, but the in-cycle sequence creator has a very large overhead. The final solution for racket (Ugly, because mlist doesn't have any nice things included): https://pastebin.com/aB2BLY1U
The mutable list solution (as one would write it in scheme) is more than twice as fast as the remainder one, and I expect it to be for other languages as well.
I've been looking for an example that shows how pattern matching can make code much both compact and readable. I think this does nicely. Here's an example in Scala:
(1 to 100).map(i => (i % 3, i % 5) match {
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => s"$i"
}).foreach(println)
Compare that to the rest of the examples on the page. The only one that comes close in either readability or compactness (in my opinion) is the Rust example, mainly because it's syntactically almost identical, just a bit more verbose. I'm really excited that C# 8 will support similar syntax with _ discards.
The Haskell example is quite similar to the Scala/Rust example as well. I guess you could rewrite the Haskell version to match your Scala version pretty closely as well if you prefer doing the tuple construction and then matching on the tuple, like in your Scala version, instead of doing it directly inside the pattern match.
Something like this, with the caveat that I haven't done any proper coding in Haskell in years and I don't have an interpreter installed to verify correctness.
Midnight takes your heart and your soul
While your heart is as high as your soul
Put your heart without your soul into your heart
Give back your heart
Desire is a lovestruck ladykiller
My world is nothing
Fire is ice
Hate is water
Until my world is Desire,
Build my world up
If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
Shout "FizzBuzz!"
Take it to the top
If Midnight taking my world, Fire is nothing
Shout "Fizz!"
Take it to the top
If Midnight taking my world, Hate is nothing
Say "Buzz!"
Take it to the top
Whisper my world
The "Haskell implementation using monoids" on this page is the only solution I've seen where adding a new behavior (e.g. "FizzBuzzWoof") only requires a modification in one spot.
(d 3 "Fizz" <> d 5 "Buzz")
becomes
(d 3 "Fizz" <> d 5 "Buzz" <> d 13 "Woof")
eta: And just below it is a similar solution in Python. Cool!
The Prolog version is fine, but the nested conditionals make it harder to read and may cause confusion about scope (for example, it's not necessary to enclose "divBy3(X),divBy5(X)" in parentheses, as on line 6 in the article).
Here's an alternative version, that avoids nested conditionals and also doesn't use the cut ("!") to control backtracking:
fizzbuzz(X,'Fizz'):-
0 is mod(X,3).
fizzbuzz(X,'Buzz'):-
0 is mod(X,5).
fizzbuzz(X,X):-
\+ fizzbuzz(X,'Fizz')
,\+ fizzbuzz(X,'Buzz').
print_fizzbuzz(N,M):-
N > M.
print_fizzbuzz(N,M):-
N =< M
,forall(fizzbuzz(N,FBN)
,write(FBN)
)
,nl
,succ(N,N_)
,print_fizzbuzz(N_,M).
This one uses Prolog's nondeterminsm to generate either Fizz, Buzz, both, or neither as apropriate and collects them all with forall/2 (yes, Prolog does have for-loops; of a sort), then adds a newline to the output.
The functional why was as a filter for eliminating impostors. At the time it was new, no one could look up the answers for it, because it was such an arbitrary problem. Now, it's just a curiosity.
- fibonacci sequence to n (ooh, look, isn't recursion pretty)
- parallel map (simple demonstration of parallelism in languages that allow it)
[slightly more involved, webapp hello worlds]
- basic blog (various MVC web frameworks, normally along lines of if I run commands x, y and z I get models, views and controllers and it all works)
- basic todo application (various frontend frameworks)
- basic chat application (as a realtime demonstration, generally for websockets)
The whole point of fizzbuzz is to filter for people that can just solve a tiny problem in a reasonably short time-- that's it. Most interviewers will even give some slack if the person has to look up the modulo operator or even do with out it.
If someone can't do it at all there's some kind of serious issue with the way they're approaching the problem, or perhaps they're just not capable of doing it.
But another common way for people to fail or at least get red-flagged is to over-think it and come up with a turgid solution-- like using lambda calculus!
Simple problem. Simple solution. Nothing fancy. Going against that is asking for failure.
I'm a bit confused, how did you implement let, if, else etc.? I don't really know much about the lambda calculus except for what I learned from a short youtube video.
Your bash example could be a little cleaner. Since 0 is truthy in bash and [ `expr something` ] is, for most purposes, (( )).
for i in {1..100}; do
if (( $i % 3 && $i % 5 )); then
echo FizzBuzz
elif (( $i % 3 )); then
echo Fizz
elif (( $i % 5 )); then
echo Buzz
else
echo $i
fi
done
Bash also has a decently powerful matching statement so you can do something similar to the rust example.
for i in {1..100}; do
case "$(( $i % 3 ))$(( $i % 5 ))" in
00)
echo FizzBuzz
;;
0*)
echo Fizz
;;
*0)
echo Buzz
;;
*)
echo $i
;;
esac
done
Select Case When SomeNumber % 3 = 0 and SomeNumber % 5 = 0 Then 'FizzBuzz'
When SomeNumber % 3 = 0 Then 'Fizz'
When SomeNumber % 5 = 0 Then 'Buzz'
Else Convert(VarChar(10), SomeNumber)
End As Answer
From (
Select Top 100
SomeNumber = Row_Number() Over (Order By [object_id])
From sys.all_objects
) as Answers
with Ada.Text_IO;
procedure FizzBuzz_Predicate is
subtype Div_3 is Integer
with Dynamic_Predicate => Div_3 mod 3 = 0;
subtype Div_5 is Integer
with Dynamic_Predicate => Div_5 mod 5 = 0;
begin
for i in Integer range 1 .. 99 loop
if i in Div_3 and i in Div_5 then
Ada.Text_IO.Put_Line ("FizzBuzz");
elsif i in Div_3 then
Ada.Text_IO.Put_Line ("Fizz");
elsif i in Div_5 then
Ada.Text_IO.Put_Line ("Buzz");
else
Ada.Text_IO.Put_Line (Integer'Image (i));
end if;
end loop;
end FizzBuzz_Predicate;
[+] [-] dbrgn|7 years ago|reply
The Rust example looks a bit strange, since you're matching on a variable, but don't actually use it.
Instead, you could write the match like this:
...or even like this: Furthermore, inclusive ranges can be written like this:[+] [-] thanatos_dem|7 years ago|reply
Did the author change it?
Edit: just saw the comments on the article. Yes, she did.
[+] [-] malloryerik|7 years ago|reply
[+] [-] geraldbauer|7 years ago|reply
[+] [-] romwell|7 years ago|reply
Pshaw.
This thread is utterly incomplete without Fizz Buzz Enterprise Edition™[1].
If you want to get straight to the good parts of it, just look at the Factories folder[2].
[1]https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpris...
[2]https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpris...
[+] [-] Someone|7 years ago|reply
You can also replace the array by a single string. That may or may not be faster, depending on CPU and language implementation. I think it likely is (rationale: the code writing the array to stdout either does multiple write calls, or builds up the string in memory and then does what the code writing the string does. The code writing the array need not load the string, but it needs to store the array, and that won’t be much smaller, even when it shares strings)
[+] [-] bjoli|7 years ago|reply
Edit: My initial assumption was correct, but the in-cycle sequence creator has a very large overhead. The final solution for racket (Ugly, because mlist doesn't have any nice things included): https://pastebin.com/aB2BLY1U
The mutable list solution (as one would write it in scheme) is more than twice as fast as the remainder one, and I expect it to be for other languages as well.
[+] [-] a3n|7 years ago|reply
[+] [-] andrewstellman|7 years ago|reply
[+] [-] war1025|7 years ago|reply
[+] [-] chucky|7 years ago|reply
Something like this, with the caveat that I haven't done any proper coding in Haskell in years and I don't have an interpreter installed to verify correctness.
[+] [-] unknown|7 years ago|reply
[deleted]
[+] [-] bradbeattie|7 years ago|reply
[+] [-] wolfi1|7 years ago|reply
[+] [-] userbinator|7 years ago|reply
https://github.com/jongeorge1/FizzBuzzEnterpriseEdition-CSha...
[+] [-] hashbig|7 years ago|reply
[+] [-] rafkin98|7 years ago|reply
puts (1..100).map { |i| (fb = [["Fizz"][i % 3], ["Buzz"][i % 5]].compact.join).empty? ? i : fb }
[+] [-] unknown|7 years ago|reply
[deleted]
[+] [-] leereeves|7 years ago|reply
https://github.com/dylanbeattie/rockstar
[+] [-] levi_n|7 years ago|reply
[+] [-] bash-j|7 years ago|reply
print('\n'.join([{(True, False): 'Fizz', (False, True): 'Buzz', (True, True): 'FizzBuzz'}.get((i % 3 == 0, i % 5 == 0), str(i)) for i in range(1, 101)]))
[+] [-] a3n|7 years ago|reply
[+] [-] KineticLensman|7 years ago|reply
Java, VBA, php, cobol, forth, C++, brainfuck, python, Groovu, BASIC, JavaScript, CoffeeScript, sh, PowerShell, Clojure, Ruby, C#, Haskell, ABAP, Lua, Matlab, Common Lisp, Oracle PL/SQL, Scala, F#, Bash, C, LOLCODE, golang, Enterprise Java, MySQL, Visual FoxPro, Perl, shakespeare
Of course, if you want it in Malboge [1], you can refer to a prior HN discussion [2] of FizzBuzz in multiple languages.
[0] http://wiki.c2.com/?FizzBuzzTest
[1] https://en.wikipedia.org/wiki/Malbolge
[2] https://news.ycombinator.com/item?id=4921651
[+] [-] happimess|7 years ago|reply
[+] [-] YeGoblynQueenne|7 years ago|reply
Here's one way to do it:
We can put that in a file, consult it and call learn_fizzbuzz at the Prolog repl: This will give us the fizzbuzz/2 function, mapping each integer N to {fizz,buzz,fizzbuzz,N}. Then we can simply loop over it: Note we learned a general version of fizzbuzz from only 5 positive and 4 negative examples. Just don't tell Joel Grus [2]._______
[1] https://github.com/metagol/metagol
[2] http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/
[+] [-] chrisulloa|7 years ago|reply
[+] [-] YeGoblynQueenne|7 years ago|reply
Here's an alternative version, that avoids nested conditionals and also doesn't use the cut ("!") to control backtracking:
This one uses Prolog's nondeterminsm to generate either Fizz, Buzz, both, or neither as apropriate and collects them all with forall/2 (yes, Prolog does have for-loops; of a sort), then adds a newline to the output.Call it like this:
And have a Happy New Year.[+] [-] vertline3|7 years ago|reply
Also we have the teapot, hello world, Foo Bar
What are some others?
[+] [-] dabent|7 years ago|reply
Atwood referenced Imran Ghory who seems to have originated the test.
[+] [-] stcredzero|7 years ago|reply
The functional why was as a filter for eliminating impostors. At the time it was new, no one could look up the answers for it, because it was such an arbitrary problem. Now, it's just a curiosity.
[+] [-] RobertKerans|7 years ago|reply
- fibonacci sequence to n (ooh, look, isn't recursion pretty) - parallel map (simple demonstration of parallelism in languages that allow it)
[slightly more involved, webapp hello worlds] - basic blog (various MVC web frameworks, normally along lines of if I run commands x, y and z I get models, views and controllers and it all works) - basic todo application (various frontend frameworks) - basic chat application (as a realtime demonstration, generally for websockets)
[+] [-] tyingq|7 years ago|reply
[+] [-] Tarean|7 years ago|reply
I always enjoy how lambda calculus suddenly becomes a readable language after the prelude:
let, if, then, else, loop, and even the numbers are all functions.[+] [-] crispyambulance|7 years ago|reply
If someone can't do it at all there's some kind of serious issue with the way they're approaching the problem, or perhaps they're just not capable of doing it.
But another common way for people to fail or at least get red-flagged is to over-think it and come up with a turgid solution-- like using lambda calculus!
Simple problem. Simple solution. Nothing fancy. Going against that is asking for failure.
[+] [-] leifmetcalf|7 years ago|reply
[+] [-] Spivak|7 years ago|reply
[+] [-] TedDallas|7 years ago|reply
[+] [-] a3n|7 years ago|reply
[+] [-] _old_dude_|7 years ago|reply
[+] [-] Narew|7 years ago|reply
[+] [-] thisacctforreal|7 years ago|reply
https://codegolf.stackexchange.com/a/148958
[+] [-] okl|7 years ago|reply