Obviously simplicity wasn't the goal of this, so don't judge me.
Created
November 15, 2012 16:53
-
-
Save ericmoritz/4079726 to your computer and use it in GitHub Desktop.
Fizzbuzz Rube Goldburg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env escript | |
%% -*- erlang -*- | |
%%! -smp enable -sname factorial -mnesia debug verbose | |
%% | |
%% "Write a program that prints the numbers from 1 to 100. But for | |
%% multiples of three print “Fizz” instead of the number and for the | |
%% multiples of five print “Buzz”. For numbers which are multiples of | |
%% both three and five print “FizzBuzz”." | |
%% http://c2.com/cgi/wiki?FizzBuzzTest | |
%% | |
main([]) -> | |
PrinterPid = spawn(fun() -> | |
printer_loop() | |
end), | |
spawn_workers(PrinterPid, 100). | |
printer_loop() -> | |
receive | |
{print, I, FizzBuzz} -> | |
io:format( | |
"~s~n", | |
[ | |
format_fizzbuzz(I, FizzBuzz) | |
]) | |
end, | |
printer_loop(). | |
spawn_workers(PrinterPid, Workers) -> | |
spawn_workers(PrinterPid, Workers, Workers). | |
spawn_workers(_, _, -1) -> | |
ok; | |
spawn_workers(PrinterPid, Workers, N) -> | |
I = Workers - N, | |
spawn(fun() -> | |
worker(PrinterPid, I+1) | |
end), | |
spawn_workers(PrinterPid, Workers, N-1). | |
worker(PrinterPid, I) -> | |
PrinterPid ! {print, I, fizzbuzz(I)}, | |
ok. | |
fizzbuzz(I) when I rem 3 == 0, I rem 5 == 0 -> | |
"FizzBuzz"; | |
fizzbuzz(I) when I rem 3 == 0 -> | |
"Fizz"; | |
fizzbuzz(I) when I rem 5 == 0 -> | |
"Buzz"; | |
fizzbuzz(_) -> | |
"". | |
-spec format_fizzbuzz(integer(), iolist()) -> iolist(). | |
format_fizzbuzz(I, "") -> | |
integer_to_list(I); | |
format_fizzbuzz(I, FizzBuzz) -> | |
FizzBuzz. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment