The Smart Person's Mirage

Are there really programmers with computer science degrees who cannot pass the FizzBuzz test

This code is given as the obvious answer

for i in range(1, 100):
if i % 3 == 0 and i % 5 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print i


Of course FizzBuzz has been golfed to death, but that is not what this question is about. You see, in the comments, someone mentions that this obvious answer is great since it's easy to add extra conditions such as print "Jazz" for multiples of 4. (I don't agree. Extending this scheme requires O(2**n) lines of code.)

Your challenge is to write the most beautiful version of FizzJazzBuzz as judged by your peers.

Some things for voters to consider:

1. DRY
2. Efficiency of division/modulus operations

Many of the answers on Quora were using Python, but there is no such language restriction here.

I'll accept the answer with the most votes one month from now

Sample output:

1
2
Fizz
Jazz
Buzz
Fizz
7
Jazz
Fizz
Buzz
11
FizzJazz
13
14
FizzBuzz
Jazz
17
Fizz
19
JazzBuzz
Fizz
22
23
FizzJazz
Buzz
26
Fizz
Jazz
29
FizzBuzz
31
Jazz
Fizz
34
Buzz
FizzJazz
37
38
Fizz
JazzBuzz
41
Fizz
43
Jazz
FizzBuzz
46
47
FizzJazz
49
Buzz
Fizz
Jazz
53
Fizz
Buzz
Jazz
Fizz
58
59
FizzJazzBuzz
61
62
Fizz
Jazz
Buzz
Fizz
67
Jazz
Fizz
Buzz
71
FizzJazz
73
74
FizzBuzz
Jazz
77
Fizz
79
JazzBuzz
Fizz
82
83
FizzJazz
Buzz
86
Fizz
Jazz
89
FizzBuzz
91
Jazz
Fizz
94
Buzz
FizzJazz
97
98
Fizz
JazzBuzz

• Your second bullet point is a bit vague... What's makes a division efficient? Why is that important for the challenge? – Sanchises Mar 4 '15 at 21:39
• @sanchises, there still exist platforms, especially microcontrollers, that have very expensive (in cycles/time) division operations. At least one of the answers below avoids division/modulus altogether - but maybe hurts readability. It's something for voters to consider. – gnibbler Mar 4 '15 at 22:07
• @sanchises not vague at all IMHO the point is not using division/modulus at all. You can do it just keeping a variable for each n=(3,4,5...) and reseting it at the time it ill match and print a word and incrementing when not. The Dry part can be doing a function/method receiving (n,word) and thus the "maintenance" of adding more words a breeze – jean Mar 6 '15 at 14:19
• You might enjoy this. – Martin Ender May 1 '15 at 21:37

The most beautiful version, you say? Then, let's try this one in...

Shakespeare Programming Language

The Marvelously Insane FizzBuzzJazz Program.

Lady Capulet, an old bossy woman that loves to count.
The Archbishop of Canterbury, an old fart who adores to spit out letters.

Act I: The only one of them.

Scene I: The Archbishop of Canterbury is a bastard.

[Enter The Archbishop of Canterbury and Lady Capulet]

The Archbishop of Canterbury:
You are nothing!

Scene II: Count, Lady Capulet, count.

The Archbishop of Canterbury:
You are as beautiful as the sum of yourself and a cat!

Am I worse than the square of the product of the sum of a warm gentle flower and a rose
and my pretty angel?

The Archbishop of Canterbury:
If not, let us proceed to Scene VIII.

Scene III: Fizzing to no end!

The Archbishop of Canterbury:
Is the remainder of the quotient between yourself and the sum of a happy cow and a
chihuahua as good as nothing?

If not, let us proceed to Scene IV. Thou art as handsome as the sum of the sum of
the sweetest reddest prettiest warm gentle peaceful fair rose and a happy proud kindgom
and a big roman. Speak thy mind!

Thou art as fair as the sum of thyself and a honest delicious cute blossoming peaceful
hamster. Thou art as cunning as the sum of the sum of an embroidered King and a horse
and thyself. Speak thy mind!

Thou art as amazing as the sum of the sum of a good happy proud rich hero and a hair and
thyself! Speak thy mind.

Scene IV: Milady, there is jazz in thy robe.

The Archbishop of Canterbury:
Is the remainder of the quotient between yourself and a proud noble kingdom as good as
nothing?

If not, let us proceed to Scene V. You are as charming as the sum of the sum of a noble
cunning gentle embroidered brave mighty King and a big warm chihuahua and an amazing

You are as prompt as the sum of yourself and a big black sweet animal. You are as noble
as the sum of the sum of a gentle trustworthy lantern and yourself and a hog. Speak your
mind!

You are as bold as the sum of the sum of yourself and a good delicious healthy sweet
horse and my smooth cute embroidered purse. You are as peaceful as the sum of a flower

Scene V: Buzz me up, Scotty!

The Archbishop of Canterbury:
Is the remainder of the quotient between yourself and the sum of a gentle happy cow and a
chihuahua as good as nothing?

If not, let us proceed to Scene VI. Thou art as handsome as the sum of the sweetest
reddest prettiest warm gentle peaceful fair rose and a small town. Speak your mind!

You are as prompt as the sum of yourself and a big healthy peaceful fair rich kingdom.
You are as loving as the sum of the sum of an embroidered King and a horse and thyself.
You are as amazing as the sum of yourself and a cute fine smooth sweet hamster. Speak

You are as prompt as the sum of the sum of yourself and an amazing cunning Lord and a

The Archbishop of Canterbury:
Let us proceed to Scene VII.

Scene VI: Output or die!

The Archbishop of Canterbury:

Scene VII: Oh, to jump the line.

You are as handsome as the sum of a proud noble rich kingdom and a rural town. Speak your
mind! You are as gentle as the sum of the sum of yourself and a green mistletoe and my

The Archbishop of Canterbury:

Scene VIII: Goodbye, cruel world!

[Exeunt]


So, after my struggle with SPL here, I felt like I had to do at least one submission with it on any challenge. And this is it.

So, what's all this then?

So, first, we declare the variables we're going to use throughout the program, which must come from Shakespeare plays. Fed up of Romeo, Juliet, Ophelia and Othello, I went up with The Archbishop of Canterbury and Lady Capulet. Their descriptions, as well as the Acts'/Scenes' titles, are disgarded by the parser, so you can put there pretty much anything you like.

So, let's make some king of translation to something a little less gibberishy.

Act I, Scene I

Begin Lady Capulet = 0;

Act I is pretty straightforward: we initialize our variable with 0.

Act I, Scene II

Lady Capulet += 1; if(Lady Capulet < Math.pow((2*2*1+1)*(2*1),2)) continue; else goto Scene VIII;

We increment Lady Capulet's value and compare it with 100 (yes, that whole sentence serves solely to get the number 100); if it's not smaller, we jump to Scene VIII (the end); otherwise, we continue on to the next Scene.

Act I, Scene III

if(Lady Capulet % (2+1) == 0) continue; else goto Scene IV; The Archbishop of Canterbury = 2*2*2*2*2*2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*2*1; The Archbishop of Canterbury += 2*1+1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*1+1; System.out.print((char)The Archbishop of Canterbury); System.out.print((char)The Archbishop of Canterbury);

First, we see if the modulus of the division by 3 is 0; if it's not, we jump to Scene IV; if it is, we begin doing arithmetic operations and storing them on the Archieperson, outputting them in character form once we find the one we're looking for. Yes, in the end, the idea is to get Fizz.

Act I, Scene IV

if(Lady Capulet % (2*2) == 0) continue; else goto Scene V; The Archbishop of Canterbury = 2*2*2*2*2*2*1+2*2*1+2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*1; The Archbishop of Canterbury += 2*2*1+(-1); System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*1+2*2*2*1; The Archbishop of Canterbury += 1; System.out.print((char)The Archbishop of Canterbury); System.out.print((char)The Archbishop of Canterbury);

First checks if the modulus of the division by 4 is 0, then continues as the same scene as before, for Jazz.

Act I, Scene V

if(Lady Capulet % (2*2+1) == 0) continue; else goto Scene VI; The Archbishop of Canterbury = 2*2*2*2*2*2*1+2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2*2*2*2*1; The Archbishop of Canterbury += 2*1+1; The Archbishop of Canterbury += 2*2*2*2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*2+1; System.out.print((char)The Archbishop of Canterbury); System.out.print((char)The Archbishop of Canterbury); goto Scene VII;

Functions like the previous two, checking if the modulus of the division by 5 returns 0, then attempts to write Buzz; the only difference is that, in the end, we skip a Scene.

Act I, Scene VI

System.out.print(Lady Capulet);

To reach this Scene, the number assumed by Lady Capulet must not have been neither Fizz nor Jazz nor Buzz; so, we output it in numeric form.

Act I, Scene VII

The Archbishop of Canterbury = 2*2*2*1+2*1; System.out.print((char)The Archbishop of Canterbury); The Archbishop of Canterbury += 2*1+1; System.out.print((char)The Archbishop of Canterbury); goto Scene II;

So, this is the only way I found to jump to the next line: output, first, a CR, then a LF; then, we return to Scene II, to that we can continue with the program.

Act I, Scene VIII

End.

Straightforward enough.

I'm still trying to see if I could show this running online, but I can't find an online compiler - the one I know doesn't seem to combine well with any program except the one already loaded, or maybe there's some kind of problem with the interface between the keyboard and the chair...

Update 1:

After mathmandan's comment, I edited the order of Jazz's and Buzz's scenes. It had to be done.

• It looks like I have DNS issues. Sorry for the false alarm. – Rainbolt Mar 5 '15 at 20:30
• One wonders why Shakespeare never gets code-golfed. – Sanchises Mar 5 '15 at 20:45
• I was hoping that Scenes III, IV and V would correspond to Fizz, Jazz and Buzz, respectively. Still, beautifully done! – mathmandan Mar 6 '15 at 17:52
• @mathmandan Damn. What a wasted opportunity to do something brilliant. DAMN!! – Rodolfo Dias Mar 6 '15 at 18:03
• It is marvelous, but I seem to have noticed a bug. I think it outputs the number if it's not a Buzz, regardless of whether it was a Fizz or a Jazz. I didn't run it, but I can't seem to find the check for this. Maybe you could check in the end if the Archbishop is a z and reset him before every loop. – matega Mar 7 '15 at 17:25

><> (Fish)

1 > :9b*)?; 0& v
\ :3%?v "Fizz" r}oooo &1+& \
/     <                    /
\ :4%?v "Jazz" r}oooo &1+& \
/     <                    /
\ :5%?v "Buzz" r}oooo &1+& \
/     <                    /
\   &?v :n                 \
^  +1 oa           <                    /


><> is a 2D programming language where instructions are single chars and the instruction pointer (IP) can move up, down, left or right, depending on arrows ^>v< and mirrors /\. It doesn't have variables or strings so not repeating yourself is a little harder, but I think this is nice in its own way.

We push 1 and start the loop. :9b*)?; checks if the number is greater than 99 (9b* = 9*11), and if so the program halts ;. Otherwise, put a 0 into the register and move down v into the wavy part.

:3%? checks the number modulo 3. If it's nonzero, then we go down v a row and move left <. Otherwise, we skip the down arrow and push "Fizz", print it (r}oooo) and increment the register (&1+&) before bouncing off the right wall mirrors to go down a row. Either way we end up moving leftward along the third row, until we bounce off the left wall mirrors. Then we repeat for Jazz and Buzz.

This continues until the 7th line, which checks the register &'s value. If it's nonzero, then we just go down. Otherwise, we print the number itself n before going down.

Finally, ao (remember, we're moving leftward now!) prints an ASCII newline and 1+ increments the number, before we go up ^ and do the loop > again.

(Now we wait for an aesthetic Piet answer...)

• This is beautiful. This should go into the hall of fame for ><> answers. – Joshpbarron Mar 5 '15 at 10:00
• My eyes immediately jumped to the :3. – EMBLEM Mar 9 '15 at 20:03
• Well, that language isn't going to win any readability awards, but it's pretty neat. – William T Froggard Jul 3 '15 at 0:23

LOLCODE

Elegant? Nope. Efficient? Definitely not. Beautiful? Well, you know what they say: beauty is in the eye of the beholder.

HAI
I HAS A kitty ITZ 1
IM IN YR house UPPIN YR kitty TIL BOTH SAEM kitty AN 100

BTW, computin yr mods
I HAS A d00d ITZ NOT MOD OF kitty AN 3
I HAS A doge ITZ NOT MOD OF kitty AN 4
I HAS A bro ITZ NOT MOD OF kitty AN 5

ANY OF d00d bro doge MKAY, O RLY?
YA RLY
d00d, O RLY?
YA RLY
VISIBLE "Fizz"!
OIC
doge, O RLY?
YA RLY
VISIBLE "Jazz"! BTW, wow such jazz
OIC
bro, O RLY?
YA RLY
VISIBLE "Buzz"!
OIC
NO WAI
VISIBLE kitty!
OIC

VISIBLE ""
IM OUTTA YR house
KTHXBYE


Some explanation:

LOLCODE programs begin with HAI and end with KTHXBYE.

Variables are dynamically typed and are assigned using I HAS A <variable> ITZ <value>. Once defined, variables can also be assigned using <variable> R <value>.

Loops in LOLCODE are named. The syntax is:

IM IN YR <loop> UPPIN YR <index> TIL BOTH SAEM <index> AN <end>
<stuff to do>
IM OUTTA YR <loop>


This is just Internet speak for "loop until i = end". In LOLCODE 1.2, the indexing variable needs to be initialized prior to the loop. Here the loop is named "house" because it makes reading the loop initialization sound humorous.

VISIBLE prints to stdout. By default a newline is appended, but adding ! suppresses the newline.

Conditionals are specified as follows:

<condition>, O RLY?
YA RLY
<code to execute if condition is true>
NO WAI
<code to execute if condition is false>
OIC


Conditions must either be expressions which evaluate to a boolean or boolean values. In LOLCODE, the boolean type is called TROOF and it has values WIN (true) and FAIL (false).

Single-line comments begin with BTW.

Not well-versed in the language of teh Internetz? Just let me know and I'll happily provide further explanation.

• Great. This is incredible. I'm still laughing – rpax Mar 9 '15 at 15:38
• @rpax: Excellent... All is going according to plan... – Alex A. Mar 9 '15 at 16:01

Python3

lst = [('Fizz', 3),
('Jazz', 4),
('Buzz', 5),
]

for i in range(1, 101):
print(*[w for w, m in lst if i % m == 0] or [i], sep='')

• Among the current top answer, this is the only one that has any form of Efficiency of division/modulus operations – aross Mar 9 '15 at 11:31
• @aross What do you mean? All answers I've seen uses at most the same number of division/modulus operations as this one. – Hjulle Mar 15 '15 at 1:50
• Really? All other answers use a modulus operator for each of (3, 4, 5). It is duplicated thrice. This is the only top answer with only a single modulus operator. – aross Mar 16 '15 at 8:53
• I just read the comments on the question. I guess I misinterpreted the quoted sentence. Should have referred to DRY instead. Furthermore, this answer is composed by the OP. – aross Mar 16 '15 at 9:03

Piet

I decided to try and play with Piet and see how pretty of a code I could make. I try not to repeat anything here, although to be honest I do have to repeat the mod calculations. However, each distinct mod (n % 3, n % 4, and n % 5) are only ever run once per iteration of code.

The smaller image is the proper source, and can be uploaded and run here.

Enjoy!

• "Are there really programmers with computer science degrees who cannot pass the FizzBuzz test in Piet?" – Sanchises Mar 13 '15 at 8:08

Mathematica

In Mathematica you can define and overload functions for very specific parameters (not only by type, but also by arbitrary logical conditions). Let's define a few functions:

Fizz[n_, s___] := {n, s}
Fizz[n_ /; Divisible[n, 3], s___] := {n, "Fizz" <> s}
Jazz[n_, s___] := {n, s}
Jazz[n_ /; Divisible[n, 4], s___] := {n, "Jazz" <> s}
Buzz[n_, s___] := {n, s}
Buzz[n_ /; Divisible[n, 5], s___] := {n, "Buzz" <> s}
DoThe[n_] := n
DoThe[_, s_] := s


And now the actual program is merely

DoThe @@@ Fizz @@@ Jazz @@@ Buzz /@ Range[100] // TableForm


Now while the above only grows linearly with the number of divisors, it's still not very DRY. But we can actually use variables as names in these definitions. So we can actually write a function which generates these function definitions:

addFunction[f_, divisor_] := (
f[n_, s___] := {n, s};
f[n_ /; Divisible[n, divisor], s___] := {n, ToString[f] <> s}
)
DoThe[n_] := n
DoThe[_, s_] := s

DoThe @@@ Fizz @@@ Jazz @@@ Buzz /@ Range[100] // TableForm


Now all you have to do is add another addFunction call and add your new **zz to the final line.

• DoThe @@@ Time @@@ Warp @@@ Again /@ Range[100] // TableForm – Sp3000 Mar 5 '15 at 9:33
• It's just a JMP to the left! – MikeTheLiar Mar 5 '15 at 16:00
• "all you have to do is add another addFunction call."... and add the new function to the final line? – Sparr Mar 5 '15 at 17:05
• @Sparr oh yeah that's true – Martin Ender Mar 5 '15 at 19:39

You guys aren't taking the DRY seriously. There are obvious patterns that can be factored out in the "Fizz Jazz Buzz" sequence.

import Control.Applicative

-- All words end with "zz" and the numbers are in a sequence
fizzes = zip [3..] $(++ replicate 2 'z') <$> words "Fi Ja Bu"

main = putStrLn . unlines $fizzIt <$> [1..99]

-- unnecessary repetition of variable names
fizzIt = nonFizzy =<< fizzy

-- Show the number if no fizziness was found. Partially point free
-- with respect to n. But xs is needed to prevent the error:
-- "Equations for ‘nonFizzy’ have different numbers of arguments"
nonFizzy "" = show
nonFizzy xs = const xs

-- (Ab)use the list monad for concatenating the strings

fizzy i = snd =<< filter ((==0).mod i.fst) fizzes
-- Could also be written as:
-- > fizzy i = concat [ str | (n,str) <- fizzes, imodn==0]
-- but that would be way too readable, and not pointless (ahem, point free) enough. ;)


This code is also easily extensible. To solve the "Fizz Jazz Buzz Tizz" problem, all you need to do is add Ti after the Bu in the string. This is much less than what is needed in any of the other solutions.

• What if you had to solve the Fizz-Jazz-Buzz-Sausage problem? – Anko Mar 6 '15 at 0:15
• @Anko I could either do something like this fizzes = zip [3..] $((++ replicate 2 'z') <$> words "Fi Ja Bu") ++ ["Sausage"], or just revert to fizzes = zip [3..] $words "Fizz Jazz Buzz Sausage". – Hjulle Mar 6 '15 at 6:47 • replicate 2 z is stretching it a bit . . . – Soham Chowdhury Mar 25 '15 at 11:11 • @octatoan I couldn't resist. ;) – Hjulle Mar 26 '15 at 0:17 Excel VBA  Sub scopeeeeeeeeeeeeeeee() ' || For u = 1 To 100 If u Mod 3 = 0 Then yell = "Fizz" If u Mod 4 = 0 Then yell = yell & "Jazz" '---------------------------------------------| If u Mod 5 = 0 Then yell = yell & "Buzz" '---------------------------------------------| 'made in USA If yell = "" Then yell = u Debug.Print yell '\\ yell = "" '\\ Next '\\ End Sub '\\  It might sounds stupid, but it's a 2D sniper rifle! • Half of it.!!!! – Optimizer Mar 6 '15 at 16:41 • Also, this is funny - "If you mode 3" – Optimizer Mar 6 '15 at 16:41 • Thank you!! I didn't expect someone realize the u mode 3 part so quick – Alex Mar 6 '15 at 16:42 • I don't understand why half of it! – Alex Mar 6 '15 at 16:42 • Sniper is only half. The scope is usually at the middle of the sniper. – Optimizer Mar 6 '15 at 16:43 Java void fizzy(int limit){ String[] output = new String[limit]; Arrays.fill(output,""); List<SimpleEntry<Integer,String>> tests = new ArrayList<SimpleEntry<Integer,String>>(); tests.add(newEntry(3,"Fizz")); tests.add(newEntry(4,"Jazz")); tests.add(newEntry(5,"Buzz")); for(SimpleEntry<Integer,String> test : tests) for(int i=test.getKey();i<limit;i+=test.getKey()) output[i] += test.getValue(); for(int i=1;i<limit;i++) System.out.println(output[i].length()<1 ? i : output[i]); } SimpleEntry<Integer,String> newEntry(int key, String value){ return new SimpleEntry<Integer,String>(key,value); }  So Java isn't really considered "beautiful" by most, but that's crazy subjective so I went by the guidelines in the question: • Don't Repeat Yourself: No problem. You only need to add one line for each number. I even made a helper function so you don't have to type as much when you do (Java can be a bit verbose sometimes, if you didn't know). • Efficiency of division/modulus operations: Perfect efficiency, since there is no modulus or division at all. That's not to say that the algorithm as a whole is the most efficient (it's not), but I think it hits the bulleted points well. • It wouldn't be Java if you didn't define a class. :D – Adrian Leonhard Mar 6 '15 at 21:10 • I wanted to like a Java answer and I like this approach, but I feel like embedding code in for-statements is unnecessary obfuscation. Beautiful Java is readable Java! – Alex Pritchard Mar 8 '15 at 20:07 • @AlexPritchard I consider that a side effect of code golfing. Will fix when at a PC :) – Geobits Mar 8 '15 at 23:58 Inform 7 Inform 7 is a rule based programming language designed for interactive fiction. It is notable for being one of the most successful natural language based programming languages. See the Inform 7 language showcase for other examples and a few bits of trivia. The number printing rules are a number based rulebook. Definition: a number is fizzy if the remainder after dividing it by 3 is 0. Definition: a number is jazzy if the remainder after dividing it by 4 is 0. Definition: a number is buzzy if the remainder after dividing it by 5 is 0. A number printing rule for a fizzy number: say "Fizz"; A number printing rule for a jazzy number: say "Jazz"; A number printing rule for a buzzy number: say "Buzz"; A number printing rule for a number (called N): unless a paragraph break is pending: say N; say conditional paragraph break; To print a series of numbers from (min - a number) to (max - a number): repeat with N running from min to max: follow the number printing rules for N;  This code has the advantage that each of the FizzBuzz rules are completely independent: additional rules can be added at any point without needing to change the general framework. Unfortunately it's a little repetitive, especially with the definition phrases. I could define a % operator, but then it wouldn't be English. ;) This code can be run online using Playfic. Dyalog APL ∇FizzJazzBuzz;list;items;names items ← ⍳100 list ← ↑('Fizz' 3) ('Jazz' 4) ('Buzz' 5) names ← (,/ ↑(↓0=⍉list[;2]∘.|items) /¨ ⊂list[;1]) ~¨ ' ' ⎕← ↑,/↑names ,¨ (∊0=⍴¨names) ⍴¨ ⊂¨⍕¨items ∇  • DRY: there is no double code • Easy to change conditions: the names are taken from a list, in order, per divisor, with minimal change needed • Easy to change range: items can be changed to an arbitrary list of numbers • Efficient: makes use of easily parallelized list-based algorithm consisting only of side-effect free primitives. • Simple code flow: not only are there no gotos, there are no whiles or ifs either. The code is completely linear. • Secures your job: barely anybody else will be able to work on it... • What are the values of ⎕ML and ⎕IO? – FUZxxl Apr 10 '15 at 17:39 • They are both 1, which is the default. – marinus Apr 10 '15 at 17:44 C# for(int i = 1; i <= 99; i++){ string s = ""; if (i % 3 == 0) s += "Fizz"; if (i % 4 == 0) s += "Jazz"; if (i % 5 == 0) s += "Buzz"; System.Console.WriteLine(s == "" ? "" + i : s); }  Check mod, build string, print number if blank or string if not. No repeats. Only need to add condition & output for new requirements. • "No repeats"? (OK, at least the code size grows linearly with additional words.) – Anko Mar 6 '15 at 0:22 • I took the challenge of no repeats a bit further with my C# answer, but sacrificed any flexibility when it comes to which numbers to modulus on. I think the best result would be a datastructure relating number and word. – sydan Mar 6 '15 at 10:49 • @Anko Not sure what you are getting at, no function is repeated. I'm not doing the same thing twice anywhere in the code. – rapjr11 Mar 6 '15 at 20:08 • @rapjr11 The code checks i-%-something many times, as well as appending to s many times. (Lots of the syntax is repetitive too, but that's probably C#'s fault.) – Anko Mar 6 '15 at 20:17 Python 2.7 I tried to make it poetic... I'm not very good at love poetry... of = 1 my_love = 100 youre = "ever" #You are for ever in range(of, my_love) : never = "out my mind" for I,am in[#audibly (3, "Fizzing"), (4, "Jazzing"), #and (5, "Buzzing")]: if( ever % I ==0):# near you never += am #I lonely. #because youre = ever #in my mind. if( youre, never == ever,"out my mind" ): never += str(youre) #(I gave up with this line...) #then our foot- print"""s will"""( never [11:3])# part.  It would also be a lot better without the initial constants :P • Creative, but this doesn't run for me in Python 2.7.9. It says: TypeError: 'str' object is not callable. – Alex A. Mar 18 '15 at 14:42 • Hmmmm... Damn... Not entirely sure how I missed that :/ – JamJar00 Mar 18 '15 at 19:34 Java with classes The algorithm: public static void main(String... args) { List<Condition> conditions = new ArrayList<Condition>(); conditions.add(new TerminatingCondition(100)); conditions.add(new ModuloCondition(3, "Fizz")); conditions.add(new ModuloCondition(4, "Jazz")); conditions.add(new ModuloCondition(5, "Buzz")); conditions.add(new EchoCondition()); while (true) { for (Condition c : conditions){ c.apply(); } } }  The classes: interface Condition { void apply(); } static class ModuloCondition implements Condition { int modulo, count = 0; String message; ModuloCondition(int modulo, String message){ this.modulo = modulo; this.message = message; } public void apply() { count++; if (count == modulo) { out.append(message); count = 0; } } } static class TerminatingCondition implements Condition { int limit, count = 0; TerminatingCondition(int limit) { this.limit = limit; } public void apply() { count++; if (count > limit) { System.exit(0); } } } static class EchoCondition implements Condition { int count = 0, lastOutCount = 0; public void apply() { count++; out.println((lastOutCount == out.count) ? String.valueOf(count) : ""); lastOutCount = out.count; } } static class Out { int count = 0; void append(String s) { System.out.append(s); count++; } void println(String s){ append(s + System.lineSeparator()); } } static Out out = new Out();  • +1, you have truly captured the spirit of Java coding with this 70-line FizzBuzzJazz. It's object-oriented and is written in a clearly specified, non-abbreviated, readable style. Very long. But very readable. ;^) – DLosc Apr 14 '15 at 0:05 MATLAB / Octave Of course, writing your own loops is fun for programmers, but everybody knows how tedious keeping track of indexing really is (who hasn't written for(j=i;j<n;i++) in a nested loop at least once in their lives?) MATLAB has the solution. Really, this code is not the most efficient, and certainly not code-golfed, but it is by all means a good showcase of MATLAB's more interesting functions. Octave is the GNU version of MATLAB; it is however not suitable for code-golf since it is slightly stricter with variable types, which is detrimental for code-golf. EDIT: until syntax highlighting for MATLAB exists on SE, I'm posting a version with very little comments, because else it was just a big scary block of plain text. function out = fizzjazzbuzz(n) %Initialization numberlist=1:n; fizz=cell(1,100); jazz=fizz;buzz=jazz; %Complex loops - no, wait, easy logical indexing. fizz(~mod(numberlist,3))={'Fizz'}; jazz(~mod(numberlist,4))={'Jazz'}; buzz(~mod(numberlist,5))={'Buzz'}; out=strcat(fizz,buzz,jazz); %Fill with numbers out(cellfun(@isempty,out))=num2cell(numberlist(cellfun(@isempty,out))); %Pretty output (although the default printing is perfectly acceptable) out=cellfun(@num2str,out,'UniformOutput',0); strjoin(out,sprintf('\n')); end  • for(j=i;j<n;i++)? My question is: who did write this "at least once in their lives"? If you did, I have bad new for you... – Bogdan Alexandru Mar 6 '15 at 10:34 • @BogdanAlexandru You have never ever in your life accidentally incremented the wrong variable in a for loop (e.g. when nesting loops)? Are you the guy whose code successfully compiles every first time? If you are, I have god news for you... – Sanchises Mar 6 '15 at 11:41 • I'm not talking about incrementing the wrong variable, my code is not god-written. I'm talking about that coding style, it's in itself very error prone. The j name for a loop local variable is fine, but the i name is very bad practice and that is the source of your mistake. It's not purely accidentally :) – Bogdan Alexandru Mar 6 '15 at 14:55 • @BogdanAlexandru Ah yes, I quite agree; the reason I still use this style of loop is when implementing given assignments (I'm a masters student); I rather use the index notation used by the professor in question, than to confuse the poor old man by using my own. – Sanchises Mar 7 '15 at 9:10 • It's no problem giving one letter names to indexes of a loop, but the other variables should have more meaningful names. – Bogdan Alexandru Mar 7 '15 at 14:49 Python from collections import defaultdict lst = [(3, 'Fizz'), (5, 'Buzz'), (4, 'Jazz')] word_list = defaultdict(list) for d, w in sorted(lst): for i in range(d, 100, d): word_list[i].append(w) for i in range(1, 100): print(''.join(word_list[i]) or i)  This is of course way too long. gnibbler's solution is much better. (although replacing *..., sep='' with ''.join would be more beautiful) But this is quite efficient in terms of division/modulus operations. • Why do you use sorted(lst), why not just put it in the order you need when you define it? – mbomb007 Mar 4 '15 at 15:43 • Or sort it in place before the loop. lst.sort() – Davidmh Mar 6 '15 at 21:44 Ruby 100.times do |n| l = [nil, 'Fizz', 'Jazz', 'Buzz'].select.with_index{|x, i| x && (n % (i+2)) == 0 } puts l.empty? ? n : l * '' end  • Looks like this is multiples of 2,3 and 4? – gnibbler Mar 4 '15 at 13:04 • @gnibbler Whoops, yes it is. Fixed. – Doorknob Mar 4 '15 at 13:05 Haskell inp = [(3, "Fizz"), (4, "Jazz"), (5, "Buzz")] mkList (n, str) = cycle$ replicate (n-1) "" ++ [str]

merge lists = (head =<< lists) : merge (map tail lists)

checkFJB "" n = show n
checkFJB s  _ = s

fjb = zipWith checkFJB (merge $map mkList inp) [1..] print100fjb = mapM_ putStrLn$ take 100 fjb


Yet another solution without division or modulus. fjb creates an infinite list of Fizzes, Jazzes, Buzzes and/or numbers. take any amount you want, as seen in print100fjb which prints the first 100 elements.

SQL (MySQL)

SELECT COALESCE(GROUP_CONCAT(FizzJazzBuzz.str ORDER BY FizzJazzBuzz.n SEPARATOR ''), I.id)
FROM I
LEFT JOIN (
SELECT 3 n,'Fizz' str
UNION SELECT 4, 'Jazz'
UNION SELECT 5, 'Buzz'
) FizzJazzBuzz ON I.id MOD FizzJazzBuzz.n = 0
GROUP BY I.id
ORDER BY I.id;


where I is a table with one column (id INT) containing the 100 integers.

I don't know an SQL flavor which can generate the table I easily, or can use VALUES as subqueries, which can make it much better and complete.

• You can use variables in mysql. SELECT @i:= (@i + 1) FROM mysql.help_relation, (SELECT @i:=0) v WHERE @i < 100; – slicedtoad Mar 6 '15 at 17:17
• @slicedtoad SELECT DISTINCT help_keyword_id FROM mysql.help_relation WHERE help_keyword_id>0 AND help_keyword_id<=100 also worked. But if 100 is changed to 10000, both will be broken. – jimmy23013 Mar 7 '15 at 2:25
• Just self join it if you need more rows. – slicedtoad Mar 7 '15 at 2:30
• As far as I'm aware MySQL is the only SQL dialect that doesn't have an easy row-generator option. Most can just use a recursive common table expression. – Ben Mar 7 '15 at 19:27
• @Ben But recursive ways doesn't always look good. I'll not fix my answer by changing the dialect because there is already an Oracle SQL answer. – jimmy23013 Mar 7 '15 at 23:10

Ruby

1.upto(100) do |i|

rules = { 3 => 'Fizz', 4 => 'Jazz', 5 => 'Buzz' }

print(i) unless rules.select! { |n,s| i.modulo(n) > 0 or print(s) }

puts

end


JavaScript

Perhaps not the most efficient way, but I think it's simple and pretty <3

(function fizzBuzz(iter){
var str = '';

if(!(iter % 3)) str += 'Fizz'
if(!(iter % 4)) str += 'Jazz'
if(!(iter % 5)) str += 'Buzz'

console.log(str || iter)

if(iter >= 100) return

fizzBuzz(++iter)
})(1)

Moar DRY and effin ugly :C

(function fizzBuzz(iter){
var
str,
fijabu = ['Fi','Ja','Bu']
;

(function isMod(_str,val){

if(!(iter % val)) _str += fijabu[val-3] + 'zz'

if(val >= 5) return str = _str

isMod(_str,++val)
})('',3)

console.log(str || iter)

if(iter >= 100) return

fizzBuzz(++iter)
})(1)

• Why the double-spacing? – Anko Mar 6 '15 at 0:14
• Personal Convention. I think its nicer to read. – soundyogi Mar 10 '15 at 17:07
• stevelosh.com/blog/2012/10/why-i-two-space I don't, though. – Soham Chowdhury Mar 25 '15 at 11:09
• I do it only in personal projects and for fun. Most Teams do not like it. – soundyogi Mar 26 '15 at 13:07

JavaScript

DRYish ... ;)

(function FizzJazzBuzz(iter) {
var output = ["Fi", "Ja", "Bu"];
var str = "";

output.map(function(v,i,a) {
if(!(iter%(i+3))) str += output[i] + "zz";
});

console.log(str || iter);

if(iter < 100) FizzJazzBuzz(++iter);

return;
})(1);


Utterly Stupid C#

Half the brief was 'DON'T REPEAT YOURSELF' so I took that as literally as I could with C# and that accidentally progressed into golfing the code. This is my first golf and I did it in C#, stupid I know but here's the result:

Golfed (240 232 230 chars):

namespace System{using Diagnostics;using i=Int32;using s=String;class P{static void Main(){s[] z=new s[]{"Fi","Ja","Bu"};for(i a=1;a<100;a++){s l="";for(i b=3;b<6;b++)if(a%b==0)l+=z[b-3]+"zz";Trace.WriteLine((l!="")?l:a+"");}}}}


Ungolfed:

namespace System
{
using Diagnostics;
using i = Int32;
using s = String;
class P
{
static void Main()
{
s[] z = new s[] { "Fi","Ja","Bu" };
for(i a = 1;a < 100;a++)
{
s l = "";
for(i b = 3;b < 6;b++)
if(a % b == 0)
l += z[b - 3] + "zz";
Trace.WriteLine((l != "") ? l : a+"");
}
}
}
}


The aim was to shorten any thing I had to use more than once and in general to keep the code short while producing a complete C# program. For this you will need to use VisualStudio and set the StartUp object to 'P' you will also need to look for the output in the debugging output window.

There are some serious limitations here:

• The code assumes that all words will end in 'zz'
• The code assumes that the modulus will happen consecutively (3,4,5,6...)
• The code still favours lack or repetition over true golfling, more characters are added to avoid some repeats

Python 2

I wanted to write an answer for this in some tidy Python that would show off the features of the language, comply with the DRY principle, and be fairly readable.

group = range(100)
rules = [('fizz', group[::3]), ('jazz', group[::4]), ('buzz', group[::5])]
for number in group[1:]:
labelset = ''
for label, matches in rules:
if number in matches:
labelset += label
print labelset if labelset else number


This little example shows slicing, the in operator, and the verbose but understandable ternary syntax. It does not use the modulo operator at all. It is not designed for run-time efficiency, but that was not the goal. It is designed to be short, understandable and maintainable.

• Why not use set(group[...]) in the rules? – gnibbler Mar 11 '15 at 21:44
• I was going for elegance rather than speed. Using set() would be faster in real applications of course. – Logic Knight Mar 12 '15 at 2:45

Python 2.7, 111 byte

This is my first contribution. I tried to apply some Python codegolfing tricks (string interleaving, tuple index access instead of if). If you have any suggestion, please share them!

for i in range(1,101):
p=""
for x in 3,4,5:
if not(i%x):p+="FJBiauzzzzzz"[x-3::3]
print((p,i)[not len(p)])


Output :

1
2
Fizz
Jazz
Buzz
Fizz
7
Jazz
Fizz
Buzz
11
FizzJazz
13
14
FizzBuzz
Jazz
17
Fizz
19
JazzBuzz
Fizz
22
23
FizzJazz
Buzz
26
Fizz
Jazz
29
FizzBuzz
31
Jazz
Fizz
34
Buzz
FizzJazz
37
38
Fizz
JazzBuzz
41
Fizz
43
Jazz
FizzBuzz
46
47
FizzJazz
49
Buzz
Fizz
Jazz
53
Fizz
Buzz
Jazz
Fizz
58
59
FizzJazzBuzz
61
62
Fizz
Jazz
Buzz
Fizz
67
Jazz
Fizz
Buzz
71
FizzJazz
73
74
FizzBuzz
Jazz
77
Fizz
79
JazzBuzz
Fizz
82
83
FizzJazz
Buzz
86
Fizz
Jazz
89
FizzBuzz
91
Jazz
Fizz
94
Buzz
FizzJazz
97
98
Fizz
JazzBuzz


I also couldn't fully apply the DRY principle, since there are two for loops. There is probably a smarter way to do it!

• I can probably also use a tuple in the first for statement. Will update when I can! – Nepho Dec 26 '16 at 11:59
• Okay, so it works with the two variables in the same loop, but I go from 111 bytes to 145 : gist.github.com/Neph0/ddc7a5ad04aa083d44af5cab3f90550f – Nepho Dec 26 '16 at 12:35

Go

The concurrent FizzJazzBuzzer

package main

import (
"fmt"
"sort"
"sync"
)

var hooks map[int]string = map[int]string{
3: "Fizz",
4: "Jazz",
5: "Buzz"}

type candidate struct {
num     int
message string
}

func FizzJazzBuzzer(hooks map[int]string) (chan<- int, *sync.WaitGroup) {
var wg *sync.WaitGroup = new(sync.WaitGroup)
final := func(c chan candidate) {
for i := range c {
if i.message == "" {
fmt.Println(i.num)
} else {
fmt.Println(i.message)
}
wg.Done()
}
}
prev := make(chan candidate)
go final(prev)
var keys []int = make([]int, 0)
for k := range hooks {
keys = append(keys, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
for _, mod := range keys {
c := make(chan candidate)
s := hooks[mod]
go (func(in chan candidate, next chan candidate, mod int, s string) {
for i := range in {
if i.num%mod == 0 {
i.message += s
}
next <- i
}
})(c, prev, mod, s)
prev = c
}
in := make(chan int)
go (func(in <-chan int) {
for i := range in {
prev <- candidate{i, ""}
}
})(in)
return in, wg
}

func main() {
in, wg := FizzJazzBuzzer(hooks)
for i := 1; i < 20; i++ {
in <- i
}
wg.Wait()
}


Try it here: http://play.golang.org/p/lxaZF_oOax

It only uses one modulus per number checked and can be arbitrarily be extended to any number of, well... numbers.

You only have to make changes 3 different places to extend this, in the hooks map, the FizzJazzBuzzer function name and, of course, the call to the FizzJazzBuzzer function.

R

This creates a function which allows a user to specify pairs of words and divisors (and optionally a maximum number, with 100 as the default). The function creates a vector from 1 to the maximum number, then replaces any numbers at "fizzbuzz" positions with "", and finally pastes each word at its desired position. The function orders the list from lowest to highest number so that the lowest number will always be the first part of the "fizzbuzz". The positions are calculated using seq to create a vector starting at a given number and increasing in increments of that number until the maximum desired number is reached.

fizzbuzzer = function(max.num=100, ...){

input = list(...)
input = input[order(unlist(input))] #reorder input list by number
words = names(input)

#vector containing the result
output = seq_len(max.num)

#remove numbers at positions to contain a "fizzbuzz"
sapply(input, function(x) output[seq(x, max.num, x)] <<- "")

sapply(seq_len(length(input)), function(i) output[seq(input[[i]], max.num, input[[i]])] <<- paste0(output[seq(input[[i]], max.num, input[[i]])], words[i]))

return(output)
}


I don't think it's very beautiful, but it's easy to re-use with different parameters.

usage examples:

fizzbuzzer(fizz=3, buzz=5)
fizzbuzzer(fizz=3, buzz=5, jazz=4)
fizzbuzzer(max.num=10000, golf=10, stack=100, code=1, exchange=1000)


The output of fizzbuzzer(fizz=3, buzz=5) is:

[1] "1"        "2"        "fizz"     "4"        "buzz"     "fizz"
[7] "7"        "8"        "fizz"     "buzz"     "11"       "fizz"
[13] "13"       "14"       "fizzbuzz" "16"       "17"       "fizz"
[19] "19"       "buzz"     "fizz"     "22"       "23"       "fizz"
[25] "buzz"     "26"       "fizz"     "28"       "29"       "fizzbuzz"
[31] "31"       "32"       "fizz"     "34"       "buzz"     "fizz"
[37] "37"       "38"       "fizz"     "buzz"     "41"       "fizz"
[43] "43"       "44"       "fizzbuzz" "46"       "47"       "fizz"
[49] "49"       "buzz"     "fizz"     "52"       "53"       "fizz"
[55] "buzz"     "56"       "fizz"     "58"       "59"       "fizzbuzz"
[61] "61"       "62"       "fizz"     "64"       "buzz"     "fizz"
[67] "67"       "68"       "fizz"     "buzz"     "71"       "fizz"
[73] "73"       "74"       "fizzbuzz" "76"       "77"       "fizz"
[79] "79"       "buzz"     "fizz"     "82"       "83"       "fizz"
[85] "buzz"     "86"       "fizz"     "88"       "89"       "fizzbuzz"
[91] "91"       "92"       "fizz"     "94"       "buzz"     "fizz"
[97] "97"       "98"       "fizz"     "buzz"


(numbers in square brackets are the indices of the vector the function outputs)

No modular arithmetic is used, except in computing the least common multiple to avoid repeating unnecessary work. The string concatenations only need to be done 60 times, no matter what we set the upper limit to.

-- Don't repeat transpose from Data.List
import Data.List (transpose)

-- The desired problem
lst = [(3, "Fizz"), (4, "Jazz"), (5, "Buzz")]

-- Map a function over both sides of a tuple.
-- We could also get this from importing Bifunctor (bimap), bit it's not in the core libraries
bimap f g (x, y) = (f x, g y)

-- Make infinite lists with the word occuring only once every n items, starting with the first
fizzify = map (cycle . uncurry take . bimap id (:repeat ""))

-- Reorganize the lists so there's a single infinite list, smash the words together, and drop the first set.
fjb = tail . map concat . transpose . fizzify

-- The following two functions avoid repeating work building the lists
-- Computes the least common multiple of a list of numbers
lcms = foldr lcm 1

-- fjbLcm is just a more efficient version of fjb; they can be used interchangably
fjbLcm lst = cycle . take (lcms . map fst $lst) . fjb$ lst

-- show the number if there aren't any words
result = zipWith (\x y -> if null x then show y else x) (fjbLcm lst) [1..100]

main = print result


Replacing fjbLcm with fjb does exactly the same thing, with no arithmetic used except in [1..100] and take.

• This is essentially the same as Nimi's solution, which I didn't notice before. – Cirdec Mar 6 '15 at 8:05

Python2

Update: New version doesn't use any mod or division operations.

word_dict = {3: 'Fizz', 4: 'Jazz', 5: 'Buzz'}

def fizz_jazz_buzz(n, d):
counters = {k: k for k in d}
for i in xrange(1, n + 1):
u = ''
for k in d:
if counters[k] == i:
u += d[k]
counters[k] += k
print u or i

fizz_jazz_buzz(100, word_dict)


If you want to add another word to the test, just throw the key/value pair into the word_dict dictionary:

word_dict[7] = 'Razz'
fizz_jazz_buzz(100, word_dict)


If you want to get rid of a word, just delete it (using del) or alternatively set it to ''.

del word_dict[3]
fizz_jazz_buzz(100, word_dict)


C#

Maintainability: Just add one line per element
I iterate over each element in the dictionary, to check if it's a divisor of the current number, and adding to the string if it is.
Once finished, print the string, unless it is still null ( using the null coalescing operator ), in which case print the number plus an empty string to make it a string. ( I could use toString, but I guess that's a personal choice )

Dictionary<int, string> dict = new Dictionary<int, string>()
{
{3, "Fizz"},
{4, "Jazz"},
{5, "Buzz"}
};
for (int i = 0; i < 100; i++)
{
string msg = null;
foreach (var pair in dict)
if (i % pair.Key == 0)
msg += pair.Value;
Console.WriteLine(msg ?? i + "");
}