title: The Smart Person's Mirage

text:
# Question
Title: The Smart Person's Mirage
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

```

# Answer
> 102 votes
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.

# Answer
> 45 votes
# \>\<\> (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.

<sup>(Now we wait for an aesthetic Piet answer...)</sup>

# Answer
> 40 votes
# 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.

# Answer
> 33 votes
## 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='')

```

# Answer
> 31 votes
# 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!

# Answer
> 26 votes
# 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.

# Answer
> 22 votes
# 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.

# Answer
> 17 votes
## 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!

# Answer
> 15 votes
# 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.

# Answer
> 11 votes
# 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.

# Answer
> 8 votes
# 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

# Answer
> 7 votes
# 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 *goto*s, there are no *while*s or *if*s either. The code is completely linear.
* Secures your job: barely anybody else will be able to work on it...

# Answer
> 7 votes
# 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.

# Answer
> 5 votes
## 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();

```

# Answer
> 4 votes
# 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

```

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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

```

# Answer
> 4 votes
# 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.

# Answer
> 4 votes
# 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.

# Answer
> 3 votes
# 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)
```

# Answer
> 3 votes
# 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

```

# Answer
> 3 votes
# 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!

# Answer
> 2 votes
# 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);

```

# Answer
> 2 votes
# 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

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
## 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)

# Answer
> 1 votes
## 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`.

# Answer
> 1 votes
## 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.

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# 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 + "");
}

```

# Answer
> 1 votes
## 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

```

# Answer
> 1 votes
## 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!

# Answer
> 1 votes
# 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...

# Answer
> 1 votes
# 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`).

# Answer
> 1 votes
## 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*)

```

# Answer
> 1 votes
# 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()

```

# Answer
> 1 votes
# 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.

# Answer
> 0 votes
# 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]

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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/

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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)))

```

# Answer
> 0 votes
# 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;

```

# Answer
> 0 votes
## 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

```

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
## 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

```

# Answer
> 0 votes
**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

# Answer
> 0 votes
# 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)

```

# Answer
> 0 votes
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

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# bc, 2686 bytes

```
/*************************************************************************
*       _____ _            _               ____                          *
*      |  ___(_)________  | | __ _ _______| __ ) _   _ ________          *
*      | |_  | |_  /_  /  | |/ _` |_  /_  /  _ \| | | |_  /_  /          *
*      |  _| | |/ / / / |_| | (_| |/ / / /| |_) | |_| |/ / / /           *
*      |_|   |_/___/___\___/ \__,_/___/___|____/ \__,_/___/___|          *
*                                                                        *
*                                                                        *
*    FizzJazzBuzz function, using "professional" coding standards        *
*                                                                        *
*************************************************************************/

/* define a `bc` function that takes no input */
/* input arguments may be added in future     */

define fjb()
{
        /* set up parameters: important for futureproofing */
        target_max_iterations=100
        integer_one=1
        integer_two=1
        integer_zero=0
        integer_three=3
        integer_four=4
        integer_five=5
        true=integer_two
        false=2

        /* i: iterate from one to one hundred  */
        for(i=1;i<=target_max_iterations;i++)
        {
                /* fjb_word: flags when a word was triggered      */
                /*          initialise to false                   */
                fjb_word=false

                /* Fizz condition: test for divisibility by three */
                if(i%3==integer_zero)
                {
                        fjb_word=true
                        print "Fizz"
                }

                /* Jazz condition: test for multiple of four      */
                if(i%4==integer_zero)
                {
                        fjb_word=1
                        print "Jazz"
                }

                /* Buzz condition: test for modulus of five       */
                if(i%5==integer_zero)
                {
                        fjb_word=integer_two
                        print "Buzz"
                }

                /* Else condition: fall through to here if none   */
                /* of Fizz, Jazz, or Buzz were triggered          */
                if(fjb_word==false)
                {
                        /* print current value */
                        print i
                }

                /* But we always need to print a carriage return  */
                print "\n"
        }
        /* the function has completed, so exit */
        print "\n"
        print "fjb() exit status : "
        return integer_zero
}

```

Try it online!

# Answer
> -2 votes
# **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

---
Tags: popularity-contest, fizzbuzz
---


title: Simpson diversity index

text:
# Question
Title: Simpson diversity index
The Simpson index is a measure of diversity of a collection of items with duplicates. It is simply the probability of drawing two different items when picking without replacement uniformly at random.

With `n` items in groups of `n_1, ..., n_k` identical items, the probability of two different items is

For example, if you have 3 apples, 2 bananas, and 1 carrot, the diversity index is

`D = 1 - (6 + 2 + 0)/30 = 0.7333`

Alternatively, the number of unordered pairs of different items is `3*2 + 3*1 + 2*1 = 11` out of 15 pairs overall, and `11/15 = 0.7333`.

**Input:**

A string of characters `A` to `Z`. Or, a list of such characters. Its length will be at least 2. You may not assume it to be sorted.

**Output:**

The Simpson diversity index of characters in that string, i.e., the probability that two characters taken randomly with replacement are different. This is a number between 0 and 1 inclusive.

When outputting a float, display at least 4 digits, though terminating exact outputs like `1` or `1.0` or `0.375` are OK.

You may not use built-ins that specifically compute diversity indices or entropy measures. Actual random sampling is fine, as long as you get sufficient accuracy on the test cases.

**Test cases**

```
AAABBC 0.73333
ACBABA 0.73333
WWW 0.0
CODE 1.0
PROGRAMMING 0.94545

```

**Leaderboard**

Here's a by-language leaderboard, courtesy of Martin Büttner.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

```
function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/53455/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```

# Answer
> 5 votes
# Python 2, 72

The input may be a string or a list.

```
def f(s):l=len(s);return sum(s[i%l]<>s[i/l]for i in range(l*l))/(l-1.)/l

```

I already know that it would be 2 bytes shorter in Python 3 so please don't advise me :)

# Answer
> 5 votes
# J, 26 bytes

```
1-+/((#&:>@</.~)%&(<:*])#)

```

## the cool part

I found the counts of each character by keying `</.` the string against itself (`~` for reflexive) then counting the letters of each box.

# Answer
> 4 votes
# Pyth - 19 13 12 11 bytes

*Thanks to @isaacg for telling me about n*

Uses brute force approach with `.c` combinations function.

```
csnMK.cz2lK

```

Try it here online.

Test suite.

```
c                Float division
 s               Sum (works with True and False)
  nM             Map uniqueness
   K             Assign value to K and use value
    .c 2         Combinations of length 2
      z          Of input
 lK              Length of K

```

# Answer
> 4 votes
# SQL (PostgreSQL), 182 Bytes

As a function in postgres.

```
CREATE FUNCTION F(TEXT)RETURNS NUMERIC AS'SELECT 1-sum(d*(d-1))/(sum(d)*(sum(d)-1))FROM(SELECT COUNT(*)d FROM(SELECT*FROM regexp_split_to_table($1,''''))I(S)GROUP BY S)A'LANGUAGE SQL

```

Explanation

```
CREATE FUNCTION F(TEXT) -- Create function f taking text parameter
RETURNS NUMERIC         -- declare return type
AS'                     -- return definition
    SELECT 1-sum(d*(d-1))/(sum(d)*(sum(d)-1)) -- Calculate simpson index
    FROM(
        SELECT COUNT(*)d  -- Count occurrences of each character
        FROM(             -- Split the string into characters
            SELECT*FROM regexp_split_to_table($1,'''')
            )I(S)
        GROUP BY S        -- group on the characters
        )A
'
LANGUAGE SQL

```

Usage and Test Run

```
SELECT S, F(S)
FROM (
    VALUES
    ('AAABBC'),
    ('ACBABA'),
    ('WWW'),
    ('CODE'),
    ('PROGRAMMING')
   )I(S)

S              F
-------------- -----------------------
AAABBC         0.73333333333333333333
ACBABA         0.73333333333333333333
WWW            0.00000000000000000000
CODE           1.00000000000000000000
PROGRAMMING    0.94545454545454545455

```

# Answer
> 4 votes
# Python 3, ~~66~~ 58 Bytes

This is using the simple counting formula provided in the question, nothing too complicated. It's an anonymous lambda function, so to use it, you need to give it a name.

*Saved 8 bytes(!) thanks to Sp3000.*

```
lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s)

```

Usage:

```
>>> f=lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s)
>>> f("PROGRAMMING")
0.945454

```

or

```
>>> (lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s))("PROGRAMMING")
0.945454

```

# Answer
> 4 votes
# Javascript, 119 bytes

Today on "Komali sucks at code golf"...

```
s=>eval('q=[];for(i of new Set(s))q.push((r=s.split(i).length-1)*(r-1));1-(q.reduce((z,x)=>x+z)/((l=s.length)*(l-1)))')

```

Test cases:

```
let s1= "AAABBC"
let s2 = "ACBABA"
let s3 = "WWW";
let s4 = "CODE";
let s5 = "PROGRAMMING"
let f =
s=>eval('q=[];for(i of new Set(s))q.push((r=s.split(i).length-1)*(r-1));1-(q.reduce((z,x)=>x+z)/((l=s.length)*(l-1)))')

console.log(f(s1))
console.log(f(s2))
console.log(f(s3))
console.log(f(s4))
console.log(f(s5))
```
Came across this question while doing biology homework. There has to be ways to improve this; I only spent like half an hour golfing it...

# Answer
> 3 votes
# APL, ~~39~~ 36 bytes

```
{n←{≢⍵}⌸⍵⋄N←≢⍵⋄1-(N-⍨N×N)÷⍨+/n-⍨n×n}

```

This creates an unnamed monad.

```
{
  n ← {≢⍵}⌸⍵               ⍝ Number of occurrences of each letter
  N ← ≢⍵                   ⍝ Number of characters in the input
  1-(N-⍨N×N)÷⍨+/n-⍨n×n     ⍝ Return 1 - sum((n*n-n)/(N*N-N))
}

```

You can try it online!

# Answer
> 3 votes
## Python 3, 56

```
lambda s:sum(a!=b for a in s for b in s)/len(s)/~-len(s)

```

Counts the pairs of unequal elements, then divides by the number of such pairs.

# Answer
> 2 votes
# Pyth, 13 bytes

```
csnM*zz*lztlz

```

Pretty much a literal translation of @feersum's solution.

# Answer
> 2 votes
# CJam, 25 bytes

```
l$_e`0f=_:(.*:+\,_(*d/1\-

```

Try it online

Fairly direct implementation of the formula in the question.

Explanation:

```
l     Get input.
$     Sort it.
_     Copy for evaluation of denominator towards the end.
e`    Run-length encoding of string.
0f=   Map letter/length pairs from RLE to only length.
      We now have a list of letter counts.
_     Copy list.
:(    Map with decrement operator. Copy now contains letter counts minus 1.
.*    Vectorized multiply. Results in list of n*(n-1) for each letter.
:+    Sum vector. This is the numerator.
\     Bring copy of input string to top.
,     Calculate length.
_(    Copy and decrement.
*     Multiply. This is the denominator, n*(n-1) for the entire string.
d     Convert to double, otherwise we would get integer division.
/     Divide.
1\-   Calculate one minus result of division to get final result.

```

# Answer
> 2 votes
# K (ngn/k), 30 bytes

```
{1-+//((x=\:x)-=l)%(l-1)*l:#x}

```

33 bytes if you want it to be faster:

```
{1-(+/j x)%(j:{x*x-1})[+/x]}@#'=:

```

This is the part where not having combinators hurt k's expressiveness. Also the problem statement is wrong: the equation corresponds to taking elements *without* replacement.

Try it online!

# Answer
> 2 votes
# **JavaScript, 105 bytes**

```
f=(r,f=[],n=0,a=0)=>{for(k in [...r].map(k=>f[k]=(f[k]||0)+ ++n/n),f)a+=f[k]*(f[k]-1);return 1-a/(n*n-n)}

```

# Answer
> 2 votes
# JavaScript (Node.js), 81 bytes

```
s=>s.map(t=>s[t]=-~s[t])&&s.map(x=>(n++,a=s[x],s[x]=0,q+=a--*a),n=q=0)&&1-q/n--/n

```

Try it online!

Magic

The first part defines letters as keys of `s` by abusing that the default key is undefined, and `-~undefined` = 1. Then, we iteratively delete the dictionary entries after using them (the first time we encounter them) while incrementing `n` to count the length. Finally, we compute `1-q/n--/n`.

# Answer
> 1 votes
# J, 37 bytes

```
(1-([:+/]*<:)%+/*[:<:+/)([:+/"1~.=/])

```

but I believe it can be still shortened.

Example

```
(1-([:+/]*<:)%+/*[:<:+/)([:+/"1~.=/]) 'AAABBC'

```

This is just a tacit version of the following function:

```
   fun =: 3 : 0
a1=.+/"1 (~.y)=/y
N=.(+/a1)*(<:+/a1)
n=.a1*a1-1
1-(+/n)%N
)

```

# Answer
> 1 votes
# C,89

Score is for the function `f` only and excludes unnecessary whitespace, which is only included for clarity. the `main` function is only for testing.

```
i,c,n;
float f(char*v){
  n=strlen(v);
  for(i=n*n;i--;)c+=v[i%n]!=v[i/n];
  return 1.0*c/(n*n-n);
}

main(int C,char**V){
  printf("%f",f(V[1]));
}

```

It simply compares every character with every other character, then divides by the total number of comparisons.

# Answer
> 1 votes
# CJam, 23 bytes

```
1r$e`{0=,~}%_:+\,,:+d/-

```

Byte-wise, this is a very minor improvement over @RetoKoradi's answer, but it uses a neat trick:

The sum of the first **n** non-negative integers equals **n(n - 1)/2**, which we can use to calculate the numerator and denominator, both divided by **2**, of the fraction in the question's formula.

Try it online in the CJam interpreter.

### How it works

```
 r$                     e# Read a token from STDIN and sort it.
   e`                   e# Perform run-length encoding.
     {    }%            e# For each [length character] pair:
      0=                e#   Retrieve the length of the run (L).
        ,~              e#   Push 0 1 2 ... L-1.
                        e# Collect all results in an array.
            _:+         e# Push the sum of the entries of a copy.
               \,       e# Push the length of the array (L).
                 ,:+    e# Push 0 + 1 + 2 + ... + L-1 = L(L-1)/2.
                    d/  e# Cast to Double and divide.
1                     - e# Subtract the result from 1.

```

# Answer
> 1 votes
# Haskell, 83 bytes

I know I'm late, found this, had forgotten to post. Kinda inelegant with Haskell requiring me to convert integers to numbers that you can divide by each other.

```
s z=(l(filter id p)-l z)/(l p-l z) where p=[c==d|c<-z,d<-z]
l=fromIntegral.length

```

# Answer
> 1 votes
# APL, 26 bytes

```
{1-+/÷/{⍵×⍵-1}({⍴⍵}⌸⍵),≢⍵}

```

Explanation:

* `≢⍵`: get the length of the first dimension of . Given that  is supposed to be a string, this means the length of the string.
* `{⍴⍵}⌸⍵`: for each unique element in , get the lengths of each dimension of the list of occurrences. This gives the amount of times an item occurs for each item, as a `1×≢⍵` matrix.
* `,`: concatenate the two along the horizontal axis. Since `≢⍵` is a scalar, and the other value is a column, we get a `2×≢⍵` matrix where the first column has the amount of times an item occurs for each item, and the second column has the total amount of items.
* `{⍵×⍵-1}`: for each cell in the matrix, calculate `N(N-1)`.
* `÷/`: reduce rows by division. This divides the value for each item by the value for the total.
* `+/`: sum the result for each row.
* `1-`: subtract it from 1

# Answer
> 1 votes
## PHP 4 (72 chars)

Given *$argv\[1\]* as a command line argument :

```
foreach(count_chars($argv[1])as$c)@$r-=$c*$c+$g-$g+=$c;echo$r/$g/--$g+1;

```

Try it Online

# Answer
> 1 votes
# Excel, 67 bytes

```
=LET(n,COUNTA(A:A),c,COUNTIF(A:A,UNIQUE(A:A)),1-SUM(c^2-c)/(n^2-n))

```

Input is a list of characters in the column A. One character per cell. Output is wherever the formula is which can be anywhere except in column A.

The LET() function allows you to define variables that can be referenced later and it saves most of the bytes here. The arguments are in pairs of `variable,value` except for the last argument which is not in a pair and is instead the output.

* `n,COUNTA(A:A)` stores the count of how many non-blank cells there are in column A.
* `c,COUNTIF(A:A,UNIQUE(A:A))` creates an array of all the unique items from column A and then counts how many times each of those unique values appear. Technically, the UNIQUE() array will include a `0` at the end (presuming there are blank cells in `A:A`) but COUNTIF() will return `0` for it's count so that doesn't impact the calculations.
* `1-SUM(c^2-c)/(n^2-n)` is the final output. Except for turning `a(a-1)` into `a^2-a` to save a byte, then is a straightforward implementation of the formula. The denominator could have also been `/n/(n-1)` for the same byte count but I chose the more aesthetically pleasing option.

# Answer
> 1 votes
# TI-Basic, 75 bytes

```
seq(inString(Ans,sub(Ans,I,1)),I,1,length(Ans→A
SortA(ʟA
augment({0},1 and ΔList(ʟA
seq(sum(cumSum(Ans)=I),I,0,sum(Ans
1-sum(Ans²-Ans)/(sum(Ans)²-sum(Ans

```

Takes input in `Ans` as a string. Output is stored in `Ans` and is displayed.

# Answer
> 1 votes
# Octave, 31 bytes

A port of xnor's Python answer.

```
@(s)nnz(s!=s')/(l=nnz(s))/(l-1)

```

Try it online!

# Answer
> 1 votes
# K (ngn/k), ~~24~~ 23 bytes

```
{1-/%/{x*x-1}(#'=x;#x)}

```

Try it online!

An adaption of @marinus' APL answer.

* `(#'=x;#x)` create a two item list containing: a dictionary mapping each distinct character to the number of times it appears in the input; and the length of the input string
* `{x*x-1}` multiply each value in the above list by itself minus one
* `%/` divide the (adjusted) counts of characters by the (adjusted) length of the input
* `1-/` use a minus-reduce, seeded with 1, subtracting each of the above to (implicitly) return the metric

# Answer
> 1 votes
# JavaScript, 100 bytes

```
a=>(n=a.length,1-[...new Set(a)].map(b=>((c=a.split(b).length-1)-1)*c).reduce((a,b)=>a+b)/(n*(n-1)))

```

# Answer
> 0 votes
# JavaScript, 96 bytes

```
a=>eval('h=0,c=0,o=[];for(i of a)o[i]=o[i]+1||1,c++;for(i in o)h+=(v=o[i])*(v-1);1-h/(c*(c-1))')

```

Posted this as a seperate answer since it's not an update to my older one.

# Answer
> 0 votes
# Pyt, 16 bytes

```
ĐĐỤ⇹ɔ⁻△Ʃ⇹Ł⁻△ᵮ/⁻~

```

Try it online!

Takes a list of characters

```
ĐĐ                    implicit input; Đuplicates on the stack twice
  Ụ                   get Ụnique elements
   ⇹ɔ                 get ɔount of each unique element in original list
     ⁻△               decrement count and get the corresponding triangular number n*(n-1)
       Ʃ              sum the triangular numbers
        ⇹Ł            get Łength of original list
          ⁻△          decrement and get triangular number
            ᵮ/        divide (cast to ᵮloat first due to bug in division coding)
              ⁻~      subtract one and negate (equivalent to subtracting from one)
                      implicit print

```

---
Tags: code-golf, math
---


title: Exactly two neighbors

text:
# Question
Title: Exactly two neighbors
Given as input a list of positive integers, your task is to determine if every integer present has exactly two neighbors in the list. The neighbors of a integer \\$x\\$ are the distinct integers that appear next to an \\$x\\$ anywhere in the list. For example in the list:

```
[1,3,4,4,3,2,1]

```

The number `3` has 3 neighbors `1`, `4` and `2`. So this input is not valid. The list

```
[1,2,3,1]

```

is valid because every number has exactly two neighbors.

This is a challenge, so in addition your code performing the task it must also be written so that when interpreted as a list of bytes, it passes the test itself. That is, every byte present in your source must have exactly two neighbors in your source.

You may take a list of positive integers for input in any reasonable method. Output one of two consistent distinct values. One value should only be output if the property is satisfied, the other if it is not.

This is ; the goal is to minimize the size of your source code as measured in bytes.

## Test cases

**truthy**

```
[]
[1,2,3,1]
[1,1,2,2]

```

**falsey**

```
[1]
[1,2]
[1,2,1,2]
[1,3,4,4,3,2,1]

```

# Answer
# Python, 2955 bytes

```
eval("(lalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalal("'[1 :37])mbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbmbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbdbm)]73: 1['"(lalalalalalalalalalalalalalalalalal("'[1 : : : : : : : : : : : : : : :37])mbdsdsdsdsds{u,inzp-+for*}<=2#eval("'"'[1 :3:3:3:3:3:3:3:3:3:3:3:3:3:3:37])mbds{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{s{sdsdbm)]73: 1['"'"(lave#2=<}*rof+-pzni,u{u{u{u{u{u{u{u{u{u{u{u{u{u{u{u{u{sdbmbmbmbmbmbmbmbmbmbmbmbmbmbmbm)]73: 1['"(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l(l("'[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1['"(l(l(l(l(l(l(l(l(lave#2=<}*rof+-pzni,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,i,i,i,i,inzp-+for*}<=2#eval("'[1 :37])m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)m)])])])])])]73: 1['"(lave#2=<}*rof+-pzninininininininininininininininininininznznznznznznznznzp-+for*}<=2#eval("'[1 : : : : : : : : : : : :37])mbds{u,inznzp-+for*}<=2#eval("'"'[1 :37])mbds{u,ininininininininininininininininininzpzpzpzpzpzpzpzpzpzni,u{sdbm)]73: 1['"'"(l(l(l(l(l(l(l(lave#2=<}*rof+-pzni,u{sdsdsdsdsdsdsdsdsdsdsdsdsdsdbm)]73: 1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1 :3:3:3:3:3:3:3:3:3: 1['"(lave#2=<}*rof+-+-+-+-+-+-+-+-+-+-+-+for*}<=2#eval("'[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 :37]7]7]7]7]7]7]7]7]73: 1['"(lave#2=<}*rof+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-pzni,u{sdsdsdsdsdsdsdsdsdsdsdsdsdsdbm)]73: 1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1 1['"'"(lave#2=<}*rof+-pzni,u{sdbm)]73:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:37])])])])])]73: 1['"(lave#2=<}*rof+-pzni,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u{sdsdsdsdsdsdsdsdsdsdsdsdsdsdbm)]73: 1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1[1 1['"'"(lave#2=<}*rof+-pzni,u{sdbm)]73:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:3:37])])])])])])])])]73: 1['"(lave#2=<}*rof+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-pzni,u{s{s{s{s{u,inzp-+for*}<=2#eval("'[1 :37])])])])])])])])])]73: 1['"(lave#2=<}*rofofofofofofofofofofofofofofofofofofoforororororororororororororororororororororororororororof+-pzni,u{sdbm)]73: : : : : : : : : : : : : : :37])mbds{u{u{u{u{u{u{u{u{u{u{u{u{u{u{sdbm)]73: : : : : : : : : : : : : :37])mbds{u,inininininininininininininininininininznznznzp-+for*}<=2#eval("'[1 :37])mbds{s{s{s{s{s{s{s{sdbm)]73: 1['"(lave#2=<}*r*r*r*r*r*r*r*r*r*r*r*r*rof+-pzni,u{s{s{s{s{s{s{s{sdbm)]73: 1['"'"(lave#2=<}*}*}*}*}*}*}*}*}*}*rof+-pzni,u{sdbm)])])])])])])])])])])])])])])])])])])])m)m)m)m)m)m)m)m)]73: 1['"(lave#2=<}*rofofofofofofofofofofofofofofofofofofoforororororororororororororororororororororororororororof+-pzni,u{sdbm)]73: : : : 1['"'"(lave#2=<}*rof+-pzni,u{sdbmbmbmbmbds{u,inzp-+for*}<=2#eval("'"'[1 : : : : : : : : : : : : :37])mbds{u,inininininininininininininininininininininininininininzp-+for*}<=2#eval("'[1 : : : : : : : : : : : : : : :37])mbdsdsdsdsdsdsdsdsdsdbm)]73: 1['"(lave#2=<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<}<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<=<}*rof+-pzni,u{u{u{u{u{u{u{u{u{sdbm)]73: 1['"'"(lave#2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=2=<}*rof+-pzni,u{sdbm)]73: 1['[1 : :37])

```

Attempt This Online!

D'oh!

### How (if you can be bothered)

The long string slices down to

```
lambda s:{sum([(u,m)in zip(s[:-1]+s[1:],s[1:]+s)for u in{*s}])for m in s}<={2}

```

It was generated (by computer program) by walking up and down the string

```
[1 :37])mbds{u,inzp-+for*}<=2#eval(

```

wasting just the right amount of time to get the right characters at the chosen spacing.

### A few more details:

Lets do a small example:

Let's assume our program is

```
abracadabra

```

The basic idea is arrange the unique letters in some order, UNQ = `abrcd`, say, and then do something like `ababrbrcdabrcrbadadadababrbrcda`. Because this was created by walking up and down UNQ every letter has at most two neighbours. Now, if we slice this with step = 3 we recover `abracadabra`: `AbaBrbRcdAbrCrbAdaDadAbaBrbRcdA`. Note that in order to break parity we needed UNQ to be of odd length and to wrap around.

With the wrapping around all the spare neighbour slots we might have hoped to harness in the next step are used up. We'll see in a moment that that is a bit of a problem:

We still need to wrap our magic string in an `eval` statement and do the slicing.

But if we try something like `eval("ababrbrcdabrcrbadadadababrbrcda"[ : :3])` then the characters touching the quotation marks are over-booked. They already had two neighbours, so the quotation mark is one too many.

We can try and solve this by integrating the wrapper code into UNQ: UNQ = `"[ :3])brcdeval(`

It almost works, but, of course, the single quotation mark will cause all sorts of problems when wrapping around. We could try a similar trick to the one we have already tacitly used to manage the double colon in the slicing expression: instead of `[::3]` (`:` has three neighbours) use `[ : :3]`. But with the colon we have used up the "neutral" space character already. We could try and use `tab` or even `newline` but there is one slightly neater way: use two kinds of quotes: single and double. UNQ = `"[ :3])brcdeval('` Then at every other wrap-around we have to add one wiggle over the quotes: `"...'"'"....'".....'"'"....'` etc. Python will concatenate this into one single string that contains a few occurrences of the character pair `'"`.
> 20 votes

# Answer
# Jelly, 12 bytes

```
ṢƝQ⁺€FċⱮ=2PṢ

```

Try it online!

Inspired by AndrovT's port of my original solution, and come to think of it, basically ports Kevin Cruijssen's solution from before porting that. While Vyxal and 05AB1E have a nice single-byte palindromize builtin, Jelly's is a digraph, and flanking the program with `Œ` would effectively comment the whole thing out (though it is still nominally accessible as a function, for the same byte count).

```
 Ɲ              For each pair of adjacent elements in the input,
Ṣ               yield it sorted.
  Q             Uniquify the list of pairs
   ⁺            then do it again
    €           to each pair.
       Ɱ  P     For every element of the input,
      ċ         is its number of occurrences in that list
     F          flattened
        =2      equal to 2?
           Ṣ    Sort the result (no-op).

```

My original solution, for posterity:

# Jelly, ~~14~~ 13 bytes

```
¹ŒḄ,ƝQFċⱮ=4P¹

```

Try it online!

*-1 porting AndrovT's Vyxal answer back*

```
 ŒḄ              Palindromize the input, making all adjacencies bidirectional.
   ,ƝQ           Find the unique pairs of adjacent elements.
        Ɱ  P     For every element of the input,
       ċ         is its number of occurrences in that list
      F          flattened
         =4      equal to 4?
¹           ¹    No-ops.

```
> 10 votes

# Answer
# Vyxal, ~~20~~ 11 bytes

```
∞2lUfvO4=A∞

```

Try it Online!

This is valid because all characters except  are used exactly once and  is both at the beginning and the end.

Now uses the same approach as @Unrelated String's Jelly answer.

```
∞2lUfvO4=A∞
∞            # palindromize
 2l          # overlapping pairs
   U         # uniquify
    f        # flatten
     vO      # for each in number input count how many times it occurs
       4=    # is equal to four?
         A   # are all true?
          ∞  # palindromize

```
> 9 votes

# Answer
# 05AB1E, ~~16~~ ~~12~~ 11 bytes

```
ûü2Ù˜s¢4QPû

```

-4 bytes thanks to *@CommandMaster*.
-1 byte porting *AndrovT*'s Vyxal answer, which is based on *@UnrelatedString*'s Jelly answer, so make sure to upvote both of them as well!

Try it online or verify all test cases or verify its own source.

**Explanation:**

```
û           # Palindromize the (implicit) input-list
 ü2         # Get all overlapping pairs of this list
   Ù        # Uniquify the pairs
    ˜       # Flatten it
     s      # Swap the (implicit) input-list to the top of the stack†
      ¢     # Count how many times each value of the input occurs in the list
       4Q   # Check for each count whether it's equal to 4 (1 if 4; 0 otherwise)
         P  # Get the product to check if all are truthy
          û # No-op palindromize (1 or 0 will remain as is)
            # (after which the result is output implicitly)

```

† Could be just `I` (push input), but with a swap it's easier to write the source verifier.
> 7 votes

# Answer
# Brachylog, ~~21~~ 20 bytes

```
s₂ᶠ{|↔ᵐ}ᵇcdhᵍlᵛ2∨?Ės

```

Try it online!

This code is self-validating because all symbols are used only once, except `s` used at the very beginning and very end.

3 bytes lost to deal with the empty list.

### Explanation

```
s₂ᶠ                    Find all sublists of 2 consecutive elements
   {|↔ᵐ}ᵇc             Append the list of reversed sublists to it
          d            Remove duplicate sublists
           hᵍ          Group by the first element of each sublist
             lᵛ2       Verify that each group has length 2
                ∨?Ė    Else: the input is the empty list
                   s   Sublist of the empty list, always succeeds (only here for self-validation constraint)

```
> 4 votes

# Answer
# Husk, 18 bytes

```
IΠmo=4`#ΣuẊe§+h↔¹I

```

Try it online!

Outputs `1` if every integer present has exactly two neighbors, `0` otherwise.
Could be 17 bytes with output as truthy (nonzero) or falsy (zero).

```
                 I  # identity = leave input unchanged
I                   # identity = leave output unchanged
 Π                  # get the product of
  m                 # mapping over the input:
   o                #   composition of 2 functions:
      `#            #     number of instances
    =4              #     equals 4
        Σ           # among all elements from
         u          # unique
          Ẋe        # adjacent pairs
            +       # in the concatenation of
             h      # the head (omit last item)
              ↔     # and the reverse
               ¹    # of the input

```
> 3 votes

# Answer
# Pyth, 24 bytes

```
!!smn2l{fPI<1T.-R]dC,tQQ

```

Try it online!

Outputs False for truthy and True for falsy. Self validating since each character is used only once except the start and end which are repeated once.

### Explanation

```
!!smn2l{fPI<1T.-R]dC,tQQQ    # implicitly add Q
                             # implicitly assign Q = eval(input())
   m                    Q    # map Q over lambda d
                   C,tQQ     #   take all pairs of adjacent elements in Q
              .-R]d          #   remove d from each pair once if possible
        f                    #   filter for pairs that are no longer pairs by looking at
         PI<1T               #     T[:-1] == T[:-1][:-1]
       {                     #   deduplicate
    n2l                      #   number of remaining elements != 2
  s                          # sum (if any elements did not have two neighbors the sum will be non zero)
!!                           # not not (takes 0 to False and non zero to True)

```
> 3 votes

# Answer
# Nibbles, 13 bytes (26 nibbles)

```
|$!=2,|`$.!>>@_:`<$?$@ ~39

```

This corresponds to the Nibbles program with bytes:

```
93 c0 1a d9 ec 9c 04 51 e3 d4 f3 40 93

```

Output is falsy (empty) if all elements have exactly 2 neighbours, truthy (nonempty list of elements that do not have exactly 2 neighbours) otherwise.

```
|$!=2,|`$.!>>@_:`<$?$@  # main program:
|                       # filter
 $                      # the input
                        # keeping elements for which
     ,|                 #   the number of
       `$.!>>@_:`<$     #   of all adjacent pairs
                   ?$@  #   that contain them
  !=2                   #   is not equal to 2

       `$.!>>@_:`<$     # adjacent pairs:
       `$               # get unique elements of
         .              #   map over
          !>>@_:        #   all adjacent pairs
                `<$     #      sorting them

~39                     # finally append nibbles 0 9 3

```
> 1 votes

# Answer
# Javascript, ~~202~~ 199 bytes

```
a=>{let o=1;a.forEach(i=>{let n=[];a.forEach((j,y)=>{if(j==i){if(y!=0)if(!n.includes(a[y-1]))n.push(a[y-1]);if(y!=a.length-1)if(!n.includes(a[y+1]))n.push(a[y+1])}});if(n.length!=2){o=0;}});return o}

```

Gets an array as input and return `1` for true and `0` for false

Ungolfed version:

```
let x = a => {
  let o = 1;
  a.forEach((i) => {
    let n = [];
    a.forEach((j, y) => {
      if (j == i) {
        if (y != 0) if (!n.includes(a[y - 1])) n.push(a[y - 1]);
        if (y != a.length - 1) if (!n.includes(a[y + 1])) n.push(a[y + 1]);
      }
    });
    if (n.length != 2) {
      o = 0;
    }
  });
  return o;
};

```

Try it online!
> 0 votes

---
Tags: code-golf, self-validating
---