The Smart Person's Mirage

29

10

Once upon a time, I was reading this question/answer on Quora

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

gnibbler

Posted 2015-03-04T10:41:09.893

Reputation: 14 170

1Your second bullet point is a bit vague... What's makes a division efficient? Why is that important for the challenge? – Sanchises – 2015-03-04T21:39:23.627

@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 – 2015-03-04T22:07:20.037

1@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 – 2015-03-06T14:19:11.773

1

Highly relevant: https://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf

– Hjulle – 2015-04-10T11:35:50.973

2You might enjoy this. – Martin Ender – 2015-05-01T21:37:11.733

"Extending this scheme requires O(2n) lines of code." How can you measure text in time complexity? – cat – 2016-03-17T21:31:00.810

@tac, good question. In a handwavy way, you have the predicate with n conditions first, then those with n-1 conditions, then n-2, etc. Since those early predicates are matched much less often, I think you'd end up with at least O(n * 2**n) time complexity. It's probably impractical to create and run the programs for more than n=20 or so – gnibbler – 2016-03-18T01:36:10.303

My bounty attracted a lot of attention, but we all know there's only one possible recipient of it. Perhaps I should leave it up for 5 days? – cat – 2016-03-19T03:09:43.860

The sample code would only print numbers 1-99. – FlipTack – 2016-12-26T12:43:04.503

Answers

101

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!

Lady Capulet:
 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?

Lady Capulet:
 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.

 Speak your 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?

Lady Capulet:
 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
 pony! Speak your mind!

 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
 and yourself. Speak your mind.

 Speak your mind!

          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?

Lady Capulet:
 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
 your mind!

 You are as prompt as the sum of the sum of yourself and an amazing cunning Lord and a
 hair. Speak your mind.

 Speak your mind!

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

          Scene VI: Output or die!

The Archbishop of Canterbury:
 Open your heart!

          Scene VII: Oh, to jump the line.

Lady Capulet:
 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
 father. Speak your mind!

The Archbishop of Canterbury:
 We must return to Scene II.

          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.

Rodolfo Dias

Posted 2015-03-04T10:41:09.893

Reputation: 3 940

Broken link in the last paragraph. – Rainbolt – 2015-03-05T20:28:49.577

@Rainbolt Hmm, odd, here loads fine. – Rodolfo Dias – 2015-03-05T20:29:41.500

1It looks like I have DNS issues. Sorry for the false alarm. – Rainbolt – 2015-03-05T20:30:28.640

17One wonders why Shakespeare never gets code-golfed. – Sanchises – 2015-03-05T20:45:14.577

5I was hoping that Scenes III, IV and V would correspond to Fizz, Jazz and Buzz, respectively. Still, beautifully done! – mathmandan – 2015-03-06T17:52:47.223

1@mathmandan Damn. What a wasted opportunity to do something brilliant. DAMN!! – Rodolfo Dias – 2015-03-06T18:03:05.193

1It 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 – 2015-03-07T17:25:10.607

@matega Good catch! I exchanged the order of two Scenes but forgot to edit the gotos. Not it should work properly :) – Rodolfo Dias – 2015-03-07T17:49:20.130

45

><> (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...)

Sp3000

Posted 2015-03-04T10:41:09.893

Reputation: 58 729

3This is beautiful. This should go into the hall of fame for ><> answers. – Joshpbarron – 2015-03-05T10:00:18.173

2My eyes immediately jumped to the :3. – EMBLEM – 2015-03-09T20:03:10.903

Well, that language isn't going to win any readability awards, but it's pretty neat. – William T Froggard – 2015-07-03T00:23:15.673

40

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.

Alex A.

Posted 2015-03-04T10:41:09.893

Reputation: 23 761

3Great. This is incredible. I'm still laughing – rpax – 2015-03-09T15:38:42.023

@rpax: Excellent... All is going according to plan... – Alex A. – 2015-03-09T16:01:04.660

33

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='')

gnibbler

Posted 2015-03-04T10:41:09.893

Reputation: 14 170

Among the current top answer, this is the only one that has any form of Efficiency of division/modulus operations – aross – 2015-03-09T11:31:22.760

@aross What do you mean? All answers I've seen uses at most the same number of division/modulus operations as this one. – Hjulle – 2015-03-15T01:50:50.200

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 – 2015-03-16T08:53:20.317

1I 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 – 2015-03-16T09:03:46.357

31

Piet

Bigger ViewActual "Source"

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!

tfitzger

Posted 2015-03-04T10:41:09.893

Reputation: 979

4"Are there really programmers with computer science degrees who cannot pass the FizzBuzz test in Piet?" – Sanchises – 2015-03-13T08:08:35.937

26

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}
)
addFunction[Fizz, 3];
addFunction[Jazz, 4];
addFunction[Buzz, 5];
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.

Martin Ender

Posted 2015-03-04T10:41:09.893

Reputation: 184 808

13DoThe @@@ Time @@@ Warp @@@ Again /@ Range[100] // TableForm – Sp3000 – 2015-03-05T09:33:52.147

10It's just a JMP to the left! – MikeTheLiar – 2015-03-05T16:00:43.570

"all you have to do is add another addFunction call."... and add the new function to the final line? – Sparr – 2015-03-05T17:05:28.177

@Sparr oh yeah that's true – Martin Ender – 2015-03-05T19:39:08.450

22

Haskell

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]

-- Point free style with reader monad ((->) a) to minimize
-- 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, i`mod`n==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.

Hjulle

Posted 2015-03-04T10:41:09.893

Reputation: 479

5What if you had to solve the Fizz-Jazz-Buzz-Sausage problem? – Anko – 2015-03-06T00:15:29.633

@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 – 2015-03-06T06:47:36.817

3replicate 2 z is stretching it a bit . . . – Soham Chowdhury – 2015-03-25T11:11:08.910

3@octatoan I couldn't resist. ;) – Hjulle – 2015-03-26T00:17:23.227

16

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!

Alex

Posted 2015-03-04T10:41:09.893

Reputation: 369

Half of it.!!!! – Optimizer – 2015-03-06T16:41:18.360

2Also, this is funny - "If you mode 3" – Optimizer – 2015-03-06T16:41:31.867

Thank you!! I didn't expect someone realize the u mode 3 part so quick – Alex – 2015-03-06T16:42:17.037

I don't understand why half of it! – Alex – 2015-03-06T16:42:38.523

Sniper is only half. The scope is usually at the middle of the sniper. – Optimizer – 2015-03-06T16:43:10.350

Yea, more of a sniper pistol ;) – Geobits – 2015-03-06T16:43:45.707

Looks more like a sniper rifle now! – Alex – 2015-03-06T16:49:32.517

15

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.

Geobits

Posted 2015-03-04T10:41:09.893

Reputation: 19 061

2It wouldn't be Java if you didn't define a class. :D – Adrian Leonhard – 2015-03-06T21:10:03.543

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 – 2015-03-08T20:07:35.033

@AlexPritchard I consider that a side effect of code golfing. Will fix when at a PC :) – Geobits – 2015-03-08T23:58:43.793

11

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.

curiousdannii

Posted 2015-03-04T10:41:09.893

Reputation: 657

7

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...

marinus

Posted 2015-03-04T10:41:09.893

Reputation: 30 224

What are the values of ⎕ML and ⎕IO? – FUZxxl – 2015-04-10T17:39:24.690

They are both 1, which is the default. – marinus – 2015-04-10T17:44:49.123

7

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.

rapjr11

Posted 2015-03-04T10:41:09.893

Reputation: 71

2"No repeats"? (OK, at least the code size grows linearly with additional words.) – Anko – 2015-03-06T00:22:25.670

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 – 2015-03-06T10:49:07.337

@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 – 2015-03-06T20:08:35.300

@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 – 2015-03-06T20:17:43.063

7

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

JamJar00

Posted 2015-03-04T10:41:09.893

Reputation: 209

Creative, but this doesn't run for me in Python 2.7.9. It says: TypeError: 'str' object is not callable. – Alex A. – 2015-03-18T14:42:54.187

Hmmmm... Damn... Not entirely sure how I missed that :/ – JamJar00 – 2015-03-18T19:34:00.577

5

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();

danixon

Posted 2015-03-04T10:41:09.893

Reputation: 151

2+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 – 2015-04-14T00:05:28.993

4

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

Sanchises

Posted 2015-03-04T10:41:09.893

Reputation: 8 530

2for(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 – 2015-03-06T10:34:34.480

1@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 – 2015-03-06T11:41:12.400

2I'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 – 2015-03-06T14:55:16.103

@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 – 2015-03-07T09:10:40.723

1It's no problem giving one letter names to indexes of a loop, but the other variables should have more meaningful names. – Bogdan Alexandru – 2015-03-07T14:49:27.657

4

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.

Jakube

Posted 2015-03-04T10:41:09.893

Reputation: 21 462

1Why do you use sorted(lst), why not just put it in the order you need when you define it? – mbomb007 – 2015-03-04T15:43:40.763

Or sort it in place before the loop. lst.sort() – Davidmh – 2015-03-06T21:44:04.603

4

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

Doorknob

Posted 2015-03-04T10:41:09.893

Reputation: 68 138

Looks like this is multiples of 2,3 and 4? – gnibbler – 2015-03-04T13:04:32.397

@gnibbler Whoops, yes it is. Fixed. – Doorknob – 2015-03-04T13:05:38.463

4

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.

nimi

Posted 2015-03-04T10:41:09.893

Reputation: 34 639

4

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.

jimmy23013

Posted 2015-03-04T10:41:09.893

Reputation: 34 042

1You can use variables in mysql. SELECT @i:= (@i + 1) FROM mysql.help_relation, (SELECT @i:=0) v WHERE @i < 100; – DanielST – 2015-03-06T17:17:28.837

@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 – 2015-03-07T02:25:55.697

1Just self join it if you need more rows. – DanielST – 2015-03-07T02:30:59.260

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 – 2015-03-07T19:27:25.220

@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 – 2015-03-07T23:10:52.287

3

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)

soundyogi

Posted 2015-03-04T10:41:09.893

Reputation: 131

8Why the double-spacing? – Anko – 2015-03-06T00:14:31.427

Personal Convention. I think its nicer to read. – soundyogi – 2015-03-10T17:07:25.470

http://stevelosh.com/blog/2012/10/why-i-two-space/ I don't, though. – Soham Chowdhury – 2015-03-25T11:09:44.083

I do it only in personal projects and for fun. Most Teams do not like it. – soundyogi – 2015-03-26T13:07:23.930

3

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

histocrat

Posted 2015-03-04T10:41:09.893

Reputation: 20 600

2

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!

Nepho

Posted 2015-03-04T10:41:09.893

Reputation: 121

I can probably also use a tuple in the first for statement. Will update when I can! – Nepho – 2016-12-26T11:59:10.253

Okay, so it works with the two variables in the same loop, but I go from 111 bytes to 145 : https://gist.github.com/Neph0/ddc7a5ad04aa083d44af5cab3f90550f

– Nepho – 2016-12-26T12:35:09.053

2

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);

Michel

Posted 2015-03-04T10:41:09.893

Reputation: 21

2

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

sydan

Posted 2015-03-04T10:41:09.893

Reputation: 171

2

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.

Logic Knight

Posted 2015-03-04T10:41:09.893

Reputation: 6 622

Why not use set(group[...]) in the rules? – gnibbler – 2015-03-11T21:44:13.963

I was going for elegance rather than speed. Using set() would be faster in real applications of course. – Logic Knight – 2015-03-12T02:45:56.177

1

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++ {
        wg.Add(1)
        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.

Kristoffer Sall-Storgaard

Posted 2015-03-04T10:41:09.893

Reputation: 489

1

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)] <<- "")

#add words at required points
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)

ping

Posted 2015-03-04T10:41:09.893

Reputation: 590

1

Haskell

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.

Cirdec

Posted 2015-03-04T10:41:09.893

Reputation: 111

This is essentially the same as Nimi's solution, which I didn't notice before.

– Cirdec – 2015-03-06T08:05:37.653

1

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)

See also the Python answers of Gnibbler and Jakube, which were posted before mine.

mathmandan

Posted 2015-03-04T10:41:09.893

Reputation: 943

1

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 + "");
}

Jack Baker

Posted 2015-03-04T10:41:09.893

Reputation: 11

1

Python

Focus on readability and easy extensibility.

from itertools import izip

def fizzBuzz():
    for components in izip(xrange(1, 101), 
                           everyNth(3, 'Fizz'), 
                           everyNth(4, 'Jazz'), 
                           everyNth(5, 'Buzz')):
        print ''.join(components[1:]) if any(components[1:]) else components[0]

def everyNth(n, returnVal):
    while True:
        for _ in xrange(n-1):
            yield ''
        yield returnVal

jlb83

Posted 2015-03-04T10:41:09.893

Reputation: 111

3Since you like itertools - everyNth is better written as cycle(chain(repeat('', n-1), [returnVal])) – gnibbler – 2015-03-07T11:48:31.267

1

Befunge-93

Not even remotely beautiful. Not easily expandable. Repeats itself. What's to like?

1v                             < v,<
 >"."96p:5%\:4%\:3%#v_0"zziF$"96p>:|
>,v                            #   $
|:<p69"$Jazz"0_v#!\ <              <
$ >          1+ 25*,           ^ v,<
>              >  \#v_0"zzuB$"96p>:|
@_^#`"b":.:         <             $<

It's Befunge, that's what to like.

Oberon

Posted 2015-03-04T10:41:09.893

Reputation: 2 881

1

Whitespace

Sadly, StackOverflow seems to ignore spaces (Those whitespace haters!). Anyway, I've replaced all spaces with S, all tabs with T and all linefeeds with L:

SSST
L
LSSST
LSSSS
LSSST
LTTSS
LSSSSTT
LTSTT
LTSSTS
L
LS
LSTT
L
LSSSTS
LSSSS
LSSSS
LTTSSSSS
LSSSTTTTSTS
LSSSTTTTSTS
LSSSTTSTSST
LSSSTSSSTTS
L
LSTSTSS
L
LSSSTT
LS
LSSSSTSS
LTSTT
LTSSTST
L
LS
LSTTS
L
LSSSTST
LSSSS
LSSSS
LTTSSSSS
LSSSTTTTSTS
LSSSTTTTSTS
LSSSTTSSSST
LSSSTSSTSTS
L
LSTSTSS
L
LSSSTTS
LS
LSSSSTST
LTSTT
LTSSTTT
L
LS
LSTSSS
L
LSSSTTT
LSSSS
LSSSS
LTTSSSSS
LSSSTTTTSTS
LSSSTTTTSTS
LSSSTTTSTST
LSSSTSSSSTS
L
LSTSTSS
L
LSSSTSSS
LSSSS
LTTT
LTSSTSST
LS
LST
LST
LSSSTSST
LSSST
LTSSSS
LSSSSTTSSTSS
LTSSTSSSTSTS
LT
LSS
LTSSTSTS
L
LS
LST
L
LSSSTSS
LS
LS
LTSSTSTT
LT
LSS
LS
LSTSS
L
LSSSTSTT
LS
L
L
LT
L
LSSSTSTS
L
L
L
L
L

I used the following code as a regex:

push 1
label loop:
push 0
push 1
store
dup
push 3
mod
jump0 fizz
jump fizznext
label fizz:
push 0
push 0
store
pushrev "Fizz" + null
call puts
label fizznext:
dup
push 4
mod
jump0 jazz
jump jazznext
label jazz:
push 0
push 0
store
pushrev "Jazz" + null
call puts
label jazznext:
dup
push 5
mod
jump0 buzz
jump buzznext
label buzz:
push 0
push 0
store
pushrev "Buzz" + null
call puts
label buzznext:
push 0
retrieve
jump0 nonenext
dup
out number
label nonenext:
push 1
add
dup
push 100
sub
push '\n'
out char
jump0 end
jump loop
label puts:
dup
jump0 return
out char
jump puts
label return:
pop
ret
label end:
stop

(Yes 3 modulus, shut up) Fun fact: The code has 0 vissible characters! And last but not least (and most surprisingly): It works!

YoYoYonnY

Posted 2015-03-04T10:41:09.893

Reputation: 1 173

1

JavaScript

a={3:'Fizz',4:'Jazz',5:'Buzz'}
for(i=1; i<100; ++i)
{
  o=''
  for(z in a) 
    if(i%z==0) 
      o+=a[z]
  console.log(o||i)
}

Here is is a good implementation of FizzJazzBuzz, trying to follow the (fuzzy) specs given. It's not good for the original FizzBuzz problem (unlike the 'obvious answer')

The FizzBuzz specific says

  • prints the numbers from 1 to 100 but
  • for multiples of three print “Fizz” instead of the number
  • for the multiples of five print “Buzz”
  • for numbers which are multiples of both three and five print “FizzBuzz” - another word literally specified. It does not say "compose a 3rd word with the first and the second)

If in the future "FizzBuzz" changes to "Spritz" most of the program here have to be heavily revised...

edc65

Posted 2015-03-04T10:41:09.893

Reputation: 31 086

1

Haskell/Skip-Halt-Print

Disclaimer: Shamelessly stolen (with permission) from: FizzBuzz in Haskell by Embedding a Domain-Specific Language by Maciej Piróg

The article shows the full derivation of the solution, which includes implementing FizzBuzz in an embedded domain specific language named "Skip-Halt-Print", and then simplify the code until that language disappears again.

Skip-Halt-Print

The language consists of the three operations, which can be shallow-embedded as:

type Program = String -> String
skip  = id       :: Program           -- Do nothing
halt  = const "" :: Program           -- Immediately halt the program
print = (++)     :: String -> Program -- Print the supplied string

Using this (and continuation-passing style) the FizzBuzz program can be written like this:

type Cont = Program → Program

fizz, buzz, base :: Int → Cont
fizz n | n `mod` 3 ≡ 0 = λx → print "fizz" ◦ x ◦ halt
       | otherwise     = id
buzz n | n `mod` 5 ≡ 0 = λx → print "buzz" ◦ x ◦ halt
       | otherwise     = id
base n                 = λx → x ◦ print (show n)

fizzbuzz :: Int → String
fizzbuzz n = (base n ◦ fizz n ◦ buzz n) skip ""

Solution

After inlining and simplifying we get the following solution:

fizzjazzbuzz :: Int → String
fizzjazzbuzz n = (test 3 "Fizz" . test 4 "Jazz" . test 5 "Buzz") id (show n)
  where
    -- test :: Int -> String -> Cont
    test d s x | n `mod` d == 0 = const (s ++ x "")
               | otherwise      = x

main :: IO ()
main = putStrLn . unlines $ map fizzjazzbuzz [1..99]

or if you want to, you can write it as

fizzes :: [(Int,String)]
fizzes = [(3,"Fizz"),(4,"Jazz"),(5,"Buzz")]

fizzjazzbuzz :: Int → String
fizzjazzbuzz n = foldr test id fizzes (show n)
  where
    -- test :: (Int, String) -> Cont
    test (d,s) x | n `mod` d == 0 = const (s ++ x "")
                 | otherwise      = x

main :: IO ()
main = putStrLn . unlines $ map fizzjazzbuzz [1..99]

Notes

One thing that is special about this solution is that it doesn't do the redundant test str == ""?str:show n, which most other solutions here does (see the article for details). This is possible because the continuation-passing gives more control over the program flow and allows the test function to choose if the number should be printed (by using halt).

Hjulle

Posted 2015-03-04T10:41:09.893

Reputation: 479

1

AppleScript

Always loved the English nature of AppleScript. I'm taking advantage of the fact that "Fizz, Jazz, Buzz" are sequential. Here's what I got:

set fjb_strings to {"Fizz", "Jazz", "Buzz"}
repeat with x from 1 to 99
    set final_string to ""
    repeat with i from 1 to length of fjb_strings
        if (x mod (i + 2)) is 0 then
            set final_string to final_string & item i of fjb_strings
        end if
    end repeat
    if final_string is equal to "" then
        set final_string to x
    end if
    log final_string
end repeat

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*)

William T Froggard

Posted 2015-03-04T10:41:09.893

Reputation: 111

Make it possible for programmers to write in English and you will find it is not possible for programmers to write in english. - Rule 00000111 of Computer Programming – cat – 2016-03-12T23:35:59.457

1

Python

My aim is not to write beautiful code as such, but instead code beautiful to Code Review.

Fizzy.py: import argparse import json

def Fizzy(ends, config, lambdas=[]):
    line = []
    for number in range(ends[0], ends[1] + 1) if len(ends) == 2 else ends:
        string = ''
        for key in config['words']:
            divisor, num, depth = int(key), number, 0
            while num % divisor == 0 and depth < config['max_repeats']:
                string += config['words'][key]
                num //= divisor
                depth += 1
        string = string if string else str(number)
        for lam in lambdas:
            string = lam(string, number)
            # TODO: include numbers ending in? e.g. 3 also matches 103, 1003, 83
        line.append(string)
    yield line


def FizzyReturn(ends, config, lambdas=[]):
    return '\n'.join(*Fizzy(ends, config, lambdas))


def FizzyPrint(ends, config, lambdas=[]):
    print(FizzyReturn(ends, config, lambdas))

if __name__ == '__main__':
    # TODO: iterator?
    parser = argparse.ArgumentParser(
        description='Return a section of the FizzBuzz sequence.')
    parser.add_argument(
        '--number', '--num', '-n', type=int, nargs=1, required=False,
        help='Number of the desired term.')
    parser.add_argument(
        '--ends', '-e', type=int, nargs=2, required=False,
        help='Start and end of the section.')
    parser.add_argument(
        '--config_path', '-c', type=str, default='Fizzy.json',
        help='Path of config JSON file. (default: Fizzy.json)')
    args = parser.parse_args()
    f = open(args.config_path)
    config = f.read()
    f.close()
    FizzyPrint(args.ends if args.ends else args.number, json.loads(config, object_pairs_hook=OrderedDict))

Fizzy.json:

{
    "max_repeats": 1,
    "words": {
        "3": "Fizz",
        "5": "Buzz"
    }
}

FizzyUnitTest.py:

import unittest
from collections import OrderedDict
from Fizzy import FizzyReturn as Fizzy

config = {
    'max_repeats': 1,
    'words': OrderedDict([('3', 'Fizz'), ('5', 'Buzz')])
}

config_repeats = {
    'max_repeats': 4,
    'words': OrderedDict([('3', 'Fizz')])
}


class TestFizzy(unittest.TestCase):
    def test_all(self):
        self.assertEqual(Fizzy([1, 15], config), '''1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz''')
        self.assertEqual(Fizzy([729], config_repeats), 'FizzFizzFizzFizz')
        self.assertEqual(
            Fizzy(
                [1, 15],
                config,
                [lambda s, n: 'A ' + s if n <= 10 else s]), '''A 1
A 2
A Fizz
A 4
A Buzz
A Fizz
A 7
A 8
A Fizz
A Buzz
11
Fizz
13
14
FizzBuzz''')

if __name__ == '__main__':
    unittest.main()

ASCII-only

Posted 2015-03-04T10:41:09.893

Reputation: 4 687

1

beeswax, 137 bytes

After solving the DRY problem for the 1,2,Fizz,4,Buzz challenge, this one was rather easy. Every mod operation is executed only once, check if n has to be printed or not (if Fizz or Jazz or both got printed before) is realized by using the global stack (gstack) as flag. If the stack is not empty, then the flag is set. Instruction f (after printing Fizz and/or Jazz) pushes the topmost local stack value onto the global stack, so if %5>0, the number only gets printed if gstack length (instruction A) is 0.

p?@<
p?{@b'gA<      p      <       p      <
q@`zzuB`d'%~5F@<f`zzaJ`b'%~4F@<f`zziF`b'%~3F<1_
 >??                        N@9P~0+.~@~-";~Pd

Adding more rules would let the source code grow only in a linear fashion.

M L

Posted 2015-03-04T10:41:09.893

Reputation: 2 865

0

DUP

For the explanation of the readable version, please scroll down ;)

I’m very sorry that I didn’t take the DRY aspect seriously enough, so here is a much better version that avoids duplication of code where not necessary:

    [/%$]⇒M['z,]⇒Z[ZZ]⇒ζ[[]]⇒β[Mβ]⇒‘[$$$3‘['F,'i,ζ]?\4‘['J,'a,ζ]?@5‘['B,'u,ζ]?**[$.]β?10,]c:0[$100<][1+c;!]#

To realize the DRY principle I made use of the operator definition functionality to simplify the program as far as possible:

Assignment of the MOD DUP combination for the three mod checks to operator M.

[/%$]⇒M


[/%$]⇒M
[$$$3M[]['F,'i,'z,'z,]?\4M[]['J,'a,'z,'z,]?@5M[]['B,'u,'z,'z,]?**[$.][]?10,]c:0[$100<][1+c;!]#

Assignment of the print single z character instruction set 'z, to operator Z.

['z,]⇒Z

[/%$]⇒M['z,]⇒Z
[$$$3M[]['F,'i,ZZ]?\4M[]['J,'a,ZZ]?@5M[]['B,'u,ZZ]?**[$.][]?10,]c:0[$100<][1+c;!]#

For even more efficient reuse of code, I assigned the duplication of Z to the operator ζ.

[ZZ]⇒ζ

[/%$]⇒M['z,]⇒Z[ZZ]⇒ζ
[$$$3M[]['F,'i,ζ]?\4M[]['J,'a,ζ]?@5M[]['B,'u,ζ]?**[$.][]?10,]c:0[$100<][1+c;!]#

And to to drive it to the max, I also assigned empty bracket pairs [] (that are used in the if-then-else constructs and while loops) to the operator β, because... why not?

[[]]⇒β

[/%$]⇒M['z,]⇒Z[ZZ]⇒ζ[[]]⇒β
[$$$3Mβ['F,'i,ζ]?\4Mβ['J,'a,ζ]?@5Mβ['B,'u,ζ]?**[$.]β?10,]c:0[$100<][1+c;!]#

It is obvious that three repetitions of are intolerable, so I assign this to the operator.

[Mβ]⇒‘

[/%$]⇒M['z,]⇒Z[ZZ]⇒ζ[[]]⇒β[Mβ]⇒‘
[$$$3‘['F,'i,ζ]?\4‘['J,'a,ζ]?@5‘['B,'u,ζ]?**[$.]β?10,]c:0[$100<][1+c;!]#

Wonderful! Compare this glorious contraption to the stale and boring old, way too inefficient and repetitive version:

[$$$3/%$[]['F,'i,'z,'z,]?\4/%$[]['J,'a,'z,'z,]?@5/%$[]['B,'u,'z,'z,]?**[$.][]?10,]c:0[$100<][1+c;!]#

In a more structured form:

[                                {function c start}
    $$$                          {duplicate value 3 times}
    3/%$[]['F,'i,'z,'z,]?        {value%3, if value%3=0 print Fizz}
    \4/%$[]['J,'a,'z,'z,]?       {swap, value%4, if value%4=0 print Jazz}
    @5/%$[]['B,'u,'z,'z,]?       {rotate, value%5, if value%5=0 print Buzz}
    **[$.][]?                    {multiply top 3 values, if result !=0 print number.}
    10,                          {print newline}
]c:                              {define function c}

0                                {start value}
[$100<][1+c;!]#                  {while value < 100, increment, call function c}

Example loop:

Assume we are are at n=6 (leads to better understandable stack values):

instr.        data stack
[
              6
$             6,6                   DUP
100           6,6,100
<             6,-1                  7<100 ? → -1 (truthy value)
]
[
1             6,1
+             7
c;!                                 push c, fetch value of c (its start value), execute c
$$$           7,7,7,7               DUP 3 times
3             7,7,7,7,3
/             7,7,7,1,2             (produces mod, div)
%             7,7,7,1               POP
$             7,7,7,1,1             DUP
[]['F,'i...]? 7,7,7,1               POP, popped value !=0, nothing is done
\             7,7,1,7               SWAP
4             7,7,1,7,4
/             7,7,1,3,1             MOD/DIV
%             7,7,1,3
$             7,7,1,3,3
[]['J,'a...]? 7,7,1,3               POP, popped value !=0, nothing is done
@             7,1,3,7               ROT
5             7,1,3,7,5
/             7,1,3,2,1
%             7,1,3,2
$             7,1,3,2,2
[]['B,'u...]? 7,1,3,2
*             7,1,6                 MUL twice. If %3,%4 or %5 were zero, the result
*             7,6                   is zero. (if Fizz, Jazz or Buzz were printed)
[                                   0 is the falsy value. So if something was printed before, the first bracket of [$.][]?                                
$             7,7                   is not entered, the number not printed.
.             7                     STDOUT: 7
][]?
10            7,10
,             7                     STDOUT: Char(10)=newline
[$100         7,7,100               continue while loop
<]            7,-1
...

Try out the code in this online DUP interpreter or clone my Julia implementation of DUP on GitHub. My GitHub page comes with a detailed explanation of DUP.

M L

Posted 2015-03-04T10:41:09.893

Reputation: 2 865

0

Haskell

-- Just an import
import Control.Applicative

-- Some fixity declarations
infix 9 %
infix 8 ?
infix 9 %?
infix 9 +?+

-- just some helper definitions
n%i = n`mod`i

0?s = s
n?s = []

i%?s = \n -> n%i?s

-- The workhorse
fjb = (((++).).(++)) <$> (3%?"Fizz") <*> (4%?"Jazz") <*> (5%?"Buzz")

-- Casework
x+?+y = if null x then y else x

-- Main routine
main = do
    mapM_ (putStrLn.((+?+) <$> fjb <*> show)) [1..99]

archaephyrryx

Posted 2015-03-04T10:41:09.893

Reputation: 1 035

4Why are you specifying the fixity of your operators, and then use parenthesis around them anyways? (3%?"Fizz") – Hjulle – 2015-03-05T14:39:44.370

0

LiveScript

[1 til 100].for-each ->
  ([[3 \Fizz] [4 \Jazz] [5 \Buzz]].reduce do
    (prev, [n, word]) -> prev + switch it % n | 0 => word
                                              | _ => ""
    "")
    console.log switch .. | "" => it
                          | _  => ..

The only annoying duplication is in the reduce-arguments prev, n, and word, but I needed them to keep the destructuring neat.

I avoided referring to the results of the reduce by using LiveScript's cascade syntax (indent, then refer to preceding expression's return as ..).

If you enjoy golf:

[1 to 99].map ->[[3 \Fizz] [4 \Jazz] [5 \Buzz]].reduce ((p,[n,w])->p+if it%n then"" else w),""
  console.log ..||it

It's a lot like Doorknob's Ruby.

Anko

Posted 2015-03-04T10:41:09.893

Reputation: 153

0

PHP

I know this isn't the most beautiful piece of code you saw this week.

But I tried to show something nice.

Here it is:

$if=function($cond, $true, $false){
    return $cond ? $true : $false;
};
$echo='printf';

for($i=1;$i<=100;$i++)
{
    "{$echo(
        $if(
            $i%5 && $i%4 && $i%3,
            $i,
            $if(!($i%3),'Fizz','').
            $if(!($i%4),'Buzz','').
            $if(!($i%5),'Jazz','')
        ).PHP_EOL
    )}";
}

This simply gives an anonymous function to a variable and a string to another one.
Inside that for loop, it has another string.

And that is where the magic happens.

You can try running it on http://writecodeonline.com/php/

Ismael Miguel

Posted 2015-03-04T10:41:09.893

Reputation: 6 797

0

Java 8

import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public enum Divisor {

    THREE(3, "Fizz"), FOUR(4, "Jazz"), FIVE(5, "Buzz");

    private final int divisor;
    private final String result;

    private Divisor(int divisor, final String result) {
        this.divisor = divisor;
        this.result = result;
    }

    public static String compute(int i) {
        final String temp = Stream.of(values())
                .filter(v -> i % v.divisor == 0)
                .map(v -> v.result)
                .collect(Collectors.joining());
        return temp.isEmpty() ? Integer.toString(i) : temp;
    }

    public static void main(String[] args) {
        process(parse(args.length > 0 ? args[0] : null, 1),
                parse(args.length > 1 ? args[1] : null, 100))
                .forEach(System.out::println);
    }

    private static int parse(final String value, int defaultValue) {
        try {
            final int result = Integer.parseInt(value);
            return result < 1 ? defaultValue : result;
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    private static Collection<String> process(int a, int b) {
        return IntStream.range(Math.min(a, b), Math.max(a, b)).mapToObj(Divisor::compute)
                .collect(Collectors.toList());
    }
}

Simply define additional divisors as a new Divisor enum value. The use of Java 8 eliminates explicit looping. The code defaults to looping between 1 and 99 inclusive, though one can over-ride that with command-line arguments.

h.j.k.

Posted 2015-03-04T10:41:09.893

Reputation: 589

0

Scala

Scala is a hybrid object-functional language on the JVM.

Solution

object FizzBuzzApp extends App {
    def fizz(i: Int) = if (i % 3 == 0) Some("Fizz") else None
    def jazz(i: Int) = if (i % 4 == 0) Some("Jazz") else None
    def buzz(i: Int) = if (i % 5 == 0) Some("Buzz") else None
    def combineFunctions(funs: ((Int) => Option[String])*)(i: Int) = {
        val result = funs.foldLeft("")((str, fun) => str + fun(i).getOrElse(""))
        if (result.isEmpty) i.toString else result
    }
    (1 to 100) map (combineFunctions(fizz, jazz, buzz)) foreach (println)
}

I hope that this is mostly comprehensible without an explanation. It could be more reusable if I used Scalaz to generalize combineFunctions to accept monoids, and folded the functions into an Option, but I'm at work at the moment.

Schalat

Posted 2015-03-04T10:41:09.893

Reputation: 373

0

Python 3

Because generators are funnier than loops

d = {3:'Fizz', 4:'Jazz', 5:'Buzz'}
print(*(''.join(d[i] for i in d if not n % i) or n for n in range(1,101)))

Evpok

Posted 2015-03-04T10:41:09.893

Reputation: 558

You should iterate over sorted(d) to make sure the words come in the correct order – gnibbler – 2015-03-08T20:07:36.080

0

Oracle SQL

To add another you just have to insert it into the mods table.

--Setup tables
create table mods (i number, s varchar2(4));
insert into mods values(3,'Fizz');
insert into mods values(4,'Jazz');
insert into mods values(5,'Buzz');

create table nums as (SELECT
    level i
      FROM DUAL
    CONNECT BY LEVEL < 100);

--Result
select 
nvl(
(
  select REPLACE(wm_concat(m.s), ',','') 
      from mods m where mod(n.i,m.i)=0
)
,n.i) from nums n;

Danny

Posted 2015-03-04T10:41:09.893

Reputation: 1 563

0

Perl5

#!/usr/bin/perl

use strict;
use warnings;

my @period;
while(<DATA>){
    /^([0-9]+)\W(.*)$/;
    push @period, {c=>$1,n=>$1,t=>$2};
}
close DATA;

foreach my $r(1..100){
    my $string=join '', map {
        if(--$_->{c}){
            ''
        }else{
            $_->{c}=$_->{n};$_->{t}
        }
    } @period;
    print $string?"$string\n":"$r\n";
}
#period <tab> value
__DATA__
3   Fizz
5   Buzz
7   Woof

hildred

Posted 2015-03-04T10:41:09.893

Reputation: 1 329

0

Python 2.7

start = 1
end = 100
output = range(0,end)
modified = [False] * end

for word, interval in [("Fizz", 3), ("Jazz", 4),("Buzz", 5)]:
    for i in range(0, end, interval):
        if modified[i]:
            output[i]+= word
        else:
            output[i] = word
            modified[i] = True

for entry in output[start:]:
    print entry

QuadmasterXLII

Posted 2015-03-04T10:41:09.893

Reputation: 881

0

Swift

Here's FizzJazzBuzz in Swift, Apple's new programming language. Again, I'm taking advantage of the fact that FizzJazzBuzz is a sequential pattern:

let fjb_strings = ["Fizz", "Jazz", "Buzz"]
for i in 1...99
{
    var final_string = ""
    for j in 1...fjb_strings.count
    {
        final_string += (i % (j+2) == 0) ? fjb_strings[j-1] : ""
    }
    print(final_string == "" ? String(i) : final_string)
}

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

William T Froggard

Posted 2015-03-04T10:41:09.893

Reputation: 111

0

Javascript

Here's a bitflag version of sorts:

function checkFive(cnum) { if ( cnum / 5 == Math.floor( cnum / 5 ) ) { return "1"; } else { return "0"; }}
function checkFour(cnum) { if ( cnum / 4 == Math.floor( cnum / 4 ) ) { return "1"; } else { return "0"; }}
function checkThree(cnum) { if ( cnum / 3 == Math.floor( cnum / 3 ) ) { return "1"; } else { return "0"; }}
function getVals(cnum) { a = ["", "", ""]; a[0] = checkThree(cnum); a[1] = checkFour(cnum); a[2] = checkFive(cnum); return [a[0], a[1], a[2]]; }
function checkAll(cnum) {
  s = ["", "Fizz", "Jazz", "Buzz"];
  b = getVals(cnum);
  c = ["", "", ""];
  if(b[0] == "0") { c[0] = s[0];} else { c[0] = s[1];}
  if(b[1] == "0") { c[1] = s[0];} else { c[1] = s[2];}
  if(b[2] == "0") { c[2] = s[0];} else { c[2] = s[3];}
  if(b[0] == "0" && b[1] == "0" && b[2] == "0") { return cnum+""; } else { return c[0] + c[1] + c[2]; }
}
var count = 0;
while (count < 100) { document.body.innerHTML = document.body.innerHTML + "<div>" + checkAll(count+1); + "</div>"; count = 1 + count; }

Here's the Fiddle

Rick Riggs

Posted 2015-03-04T10:41:09.893

Reputation: 101

0

Scala (#2)

The other scala answer is fine but I think it could use less repetition. The first goal is DRY after all.

def buzzer(v: Int, value: String) = (i: Int) =>
    if (i % v == 0) Some(value) else None
val fizz = buzzer(3, "Fizz")
val jazz = buzzer(4, "Jazz")
val buzz = buzzer(5, "Buzz")
def combine(buzzers: Int => Option[String]*) = (i: Int) =>
    buzzers.flatMap(_(i)) match {
        case Nil => i.toString
        case result => result.mkString
    }

val fizzJazzBuzz = combine(fizz, jazz, buzz)
println((1 to 100) map fizzJazzBuzz)

gladed

Posted 2015-03-04T10:41:09.893

Reputation: 159

0

A Ruby function, in functional programming style. Returns a string, that can be puts later. It's DRY; the only place to change for more "zz"s is the text hash.

def fizz_jazz_buzz
   text = {
      3 => "Fizz",
      4 => "Jazz",
      5 => "Buzz"
   }
   divide = ->(num, divisor) { num % divisor == 0 }
   (1..100).reduce("") do |acum, num|
      divisible_by = text.keys.map { |k| [k, divide.call(num, k)] }.to_h
      acum += text.select { |k, v| divisible_by[k] }.values.join
      acum += num.to_s if divisible_by.values.none? { |k| k }
      acum + "\n"
   end
end

Test code below. Should print "Pass" on passing, or "Fail" followed by the not-matching lines on failing.

def test
   expected = <<TEXT
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
TEXT
   result = fizz_jazz_buzz
   puts (result == expected) ? "Pass" : "Fail"
   a = expected.split("\n")
   b = result.split("\n")
   (0...([a.size, b.size].max)).each { |i| 
      puts "#{a[i]}   #{b[i]}" if a[i] != b[i] 
   }
end

test

jose_castro_arnaud

Posted 2015-03-04T10:41:09.893

Reputation: 229

-2

JavaScript

DRY && OO

In the lack of DRY solutions not using modulus/division I wrote it. Also it's an exercise in OO (yes, I know there's no real OO with JS)

You can see it running at JSFiddle

//FizzJazzBuzz 
var zzClass = function(){

    this.divisor;
    this.word;
    this.count;
};

zzClass.prototype = {
    isZZ : function(){
        if (this.count == this.divisor)
        {
            this.count = 1;
            return this.word;
        }
        else
        {
           this.count++;
           return '';
        }
    }
}

function initZZ(w,d)
{    
    var x = Object.create(zzClass.prototype
       , { divisor :{ value : d }, word: { value : w } }
     );

     x.count = 1;

     return x;
}

// Declare array of ZZ's
var arrZZ = [
    initZZ('Fizz',3),
    initZZ('Jazz',4),
    initZZ('Buzz',5)    
    ]

var phrase = '';

for (var i = 1; i < 101; i++)
{
    phrase = '';

    for (var j=0; j<arrZZ.length; j++)
    {
        phrase = phrase + arrZZ[j].isZZ();
    }

    if (phrase == '') phrase = i;

    console.log(phrase);
}   

We presume using a simple conditional and a variable to count when to print is "cheaper" than using modulus or division. An efficient way to calculate a minimum common multiple

jean

Posted 2015-03-04T10:41:09.893

Reputation: 177