What we think

Archives

A non-programmer’s solution to “Fizz Buzz”

Fizz Buzz is a well known programming exercise, aimed to establish simply whether someone has a basic grasp of programming concepts or not. It’s the MOT test of programming exercises, and has sparked interesting debate in the past.

Here’s an example of a Fizz Buzz question:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Example output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

etc.

I was interested in uncovering any latent programming aptitude amongst NM’s non-programming collective, so I asked some team members if they’d like to have a go at solving Fizz Buzz.

Clive took the bait, and his interpretation is below, but before reading any further, perhaps you’d like to have a go at solving Fizz Buzz as well? It’s OK, I’ll hang on for you…

dum-de-dum…

OK. Welcome back. Here’s Clive’s version, which I find fascinating…

Clive forgot to stop at 100, but apart from that the implementation’s correct. What I find fascinating is that Clive’s construction of the loop, he derives each iteration manually, whereas a seasoned programmer would simply accept the loop as a given and start from there. This may be why so many non-coders find it so hard to start coding, not knowing what you get ‘for free’ and how much you can essentially take for granted. (As an aside, this also reminded me how easy it is to dismiss the monumental effort that has gone into the creation of the technology that surrounds us, and how we so often stand on the shoulders of giants. An idea that has been explored before brilliantly in the The Toaster Project).

I also love that Clive grokked the idea of working at a “meta” level, so instead of just writing instructions like:

print “1”
print “2”
print “Fizz”

etc.

He’s actually gone to the effort of uncovering and encoding the underlying logic, which is great!

Anyway, I find this stuff fascinating, but maybe it’s just me!

Feel free to post your Fizz Buzz solutions below… Here’s mine. :)

This post was filed under Data, Technology and tagged , , , , , . Join the conversation - leave a comment.

40 Comments

  1. Jeremy Merritt

    Great read. I love thinking about how people think about solving problems.

    I posed a challenge to some coder friends to implement FizzBuzz *without* using IF statements. Here is my solution:

    http://jsfiddle.net/jeremyx/WD9hF/

    Posted 30th November 2012 at 4:49 pm | Permalink
  2. Posted 30th November 2012 at 4:55 pm | Permalink
  3. Occurred to me that this is the first pseudocode I’ve written in many many years. Fun! I think this should work but don’t think it’s very elegant. I’m guessing this is quite a basic answer, which would be about right for me :)

    For integer a = 1 to 100
    flag = 0
    If a MOD 3 = 0 then
    print ‘fizz’
    flag = 1
    End if
    If a MOD 5 = 0 then
    print ‘buzz’
    flag = 1
    End if
    If flag = 0 then
    print a
    End if
    Print linebreak
    Next a

    Posted 30th November 2012 at 6:54 pm | Permalink
  4. Simon Hawkin

    Great observation about non-coders not knowing what they can get for free. An interesting exercise overall. Thank you!

    (As an aside: in my version of Firefox the input field labels do not appear in the comment block. Is that intentional?)

    Posted 30th November 2012 at 8:00 pm | Permalink
  5. Ash

    #include

    int main(void)
    {
    int i;
    for (i = 1; i <= 100; i++)
    {
    if (!(i % 3) && !(i % 5))
    printf("FizzBuzz\n");
    else if (!(i % 3))
    printf("Fizz\n");
    else if (!(i % 5))
    printf("Buzz\n");
    else
    printf("%d\n", i);
    }
    return 0;
    }

    Posted 30th November 2012 at 9:28 pm | Permalink
  6. @Jeremy Merritt
    Here’s my FizzBuzz solution in javascript without if conditions.

    http://bateru.com/news/2012/10/code-of-the-day-fizzbuzz-in-javascript/

    Posted 30th November 2012 at 9:30 pm | Permalink
  7. Ash

    The #include was for stdio.h

    Posted 30th November 2012 at 9:30 pm | Permalink
  8. Kyle

    Not sure if this counts as not using an if statement.

    https://gist.github.com/4178425

    Posted 30th November 2012 at 9:38 pm | Permalink
  9. tonyb486

    One line of python, with no conditionals:

    print “\n”.join([str(("FizzBuzz","Fizz","Fizz","Fizz","Fizz",i,i,i,"Buzz",i,i,i,i,i,i,i,"Buzz",i,i,i,i)[(i%3<<3)|(i%5)]) for i in range(1,101)])

    Posted 30th November 2012 at 9:49 pm | Permalink
  10. scurvy

    for i in range(0,101):
    if i % 3 = 0:
    print “fizz”
    elif i % 5 = 0:
    print “buzz”
    elif i % 3 = 0 and i % 5 = 0:
    print “fizzbuzz”
    else:
    print i

    Posted 30th November 2012 at 9:52 pm | Permalink
  11. Maybe, it would be beter with the #define’s inside the asm{} block. On my whole operating system, I started with C header files and duplicate ASM declares. Then, I modified my compiler so the ASM could use C struct member names. I then had all the C headers before the asm code. The C headers also had #define’s. That’s why I got in the habit. The #defines could go inside the ASM blocks and might be better.

    Posted 30th November 2012 at 10:02 pm | Permalink
  12. No conditionals (C):

    const char *formats[] = {“%d”, “fizz”, “buzz”, “fizzbuzz”};
    for (int i = 1; i <= 100; i++) {
    printf(formats[!(i % 3) + 2 * !(i % 5)], i);
    printf("\n");
    }

    Posted 30th November 2012 at 10:20 pm | Permalink
  13. Jeremy Merritt

    @Kyle – Awesome! I love the pattern matching in Haskell

    Posted 30th November 2012 at 10:21 pm | Permalink
  14. Posted 30th November 2012 at 10:24 pm | Permalink
  15. Kyle

    @Jeremy – Technically those a guard statements and not pattern matching, but they serve much the same purpose. A similar effect could be achieved by removing the guards and adding a case statement. I’ve also seen versions implemented using list expressions, but my Haskell-Fu isn’t strong enough to do one of those properly.

    Posted 30th November 2012 at 10:29 pm | Permalink
  16. Just for fun, a one-liner in Python 3:

    print(*[not x % 15 and 'fizzbuzz\n' or not x % 3 and 'fizz\n' or not x %5 and 'buzz\n' or '%s\n' % x for x in range(1, 101)])

    Posted 30th November 2012 at 10:34 pm | Permalink
  17. If, and only if, a number is divisible by 3 and 5, it is divisible by 15.

    Clive could have saved a lot of time by stopping to consider the problem.

    Posted 30th November 2012 at 10:41 pm | Permalink
  18. Bill

    It’s always interesting that whenever FizzBuzz is mentioned, readers always feel obligated to provide their solution. Everybody solves it with a modulus operator. Seems like instead of measuring basic logic understanding, it measures proper use of the modulus operator. Should be called mod-buzz.

    Posted 30th November 2012 at 11:00 pm | Permalink
  19. I have a number of solutions, 37 in C:

    https://github.com/Keith-S-Thompson/fizzbuzz-c

    and 49 in multiple language:

    https://github.com/Keith-S-Thompson/fizzbuzz-polyglot

    (Yes, I really did use Duff’s Device in a couple of the C solutions.)

    Too much free time on my hands? Yeah.

    Posted 30th November 2012 at 11:04 pm | Permalink
  20. Josh Perez

    functional solution in JavaScript

    var three = cycle(['', '', 'fizz'])
    var five = cycle(['', '', '', '', 'buzz'])
    var fizzbuzz = zipWith(function (a, b) {
    return a + b }, three, five)

    take(100, fizzbuzz)

    Posted 1st December 2012 at 12:19 am | Permalink
  21. Mo Kouli

    javascript​

    function doFizzBuzz(start, end){

    start = start || 1;
    end = end || 100;

    if(start > end)
    return;

    for(var i=start; i<=end; i++)
    {
    var val = "";

    if(i%3 === 0)
    {
    val = "Fizz";
    }

    if(i%5 === 0)
    {
    val = val+"Buzz";
    }

    if(val.length === 0)
    {
    val = i;
    }

    console.log(val);
    }
    }

    doFizzBuzz();

    Posted 1st December 2012 at 1:02 am | Permalink
  22. @Jeremy Merritt
    > I posed a challenge to some coder
    > friends to implement FizzBuzz *without*
    > using IF statements. Here is my solution:
    > http://jsfiddle.net/jeremyx/WD9hF/

    that’s not really avoiding IF statements. you avoid the keyword IF, but you use functions like filter which very obviously use IF

    @Larry Battle
    > @Jeremy Merritt
    > Here’s my FizzBuzz solution in javascript
    > without if conditions.
    > http://bateru.com/news/2012/10/code-of-the-day-fizzbuzz-in-javascript/

    that uses ternaries, which may as well be IFs

    however, it is possible to avoid IFs completely. @Devin Lane is arguably correct, but his solution depends on parts of printf which cannot be implemented without IF (I have no proof of this, but it seems unlikely).

    Here’s my solution which only uses printf for its ability to convert ints to strings and print them rather than to change the behavior of the function using dynamic format strings.

    http://pastebin.com/Gmx8RpF8

    I can’t think of a way to do it without gotos though.

    Posted 1st December 2012 at 1:05 am | Permalink
  23. Jimle_uk

    I’ve had these on my mind for a while now…
    both one-liners are in javascript

    1. [ 'fizz' ][ x ] // returns fizz if x ==0 else undefined

    for(var i=1,j=101,x=['Fizz','Buzz'];i<j;console.log([x[0]+x[1]][i%15]||[x[1]][i%5]||[x[0]][i%3]||i),i++);

    2. create array of 101 undefined values, covert obj to str using (""+), conversion gives you a string with 101 commas (which i though was quite funny), split the string and use native foreach where x is the value (we overwrite it in this case) and y is the current index.

    note: Array(101).foreach 0&&console.log([x[0]+x[1]][y%15]||[x[1]][y%5]||[x[0]][y%3]||y);})

    Posted 1st December 2012 at 2:30 am | Permalink
  24. Jimle_uk

    sorry the last one seems cut off from some reason.

    (”+Array(101)).split(‘,’).forEach(function(x,y){x=['Fizz','Buzz'];y>0&&console.log([x[0]+x[1]][y%15]||[x[1]][y%5]||[x[0]][y%3]||y);})

    Posted 1st December 2012 at 2:31 am | Permalink
  25. twerp

    c (without using %d in a format string)

    #include // math

    void fizzbuzz(int range) {
    int i;
    char w[3][5] = {“”, “fizz”, “buzz”};
    char *s;

    for (i = 1; i <= range; i++) {
    int num_digits = (int) floor(log10(i)) + 1;
    int f = !(i % 3);
    int b = !(i % 5);
    int p = f | b;
    int j;

    s = malloc(num_digits * !p + 1);

    for (j = 0; j < (!p * num_digits); j++) {
    int digit = (i / ((int) pow(10, j))) % 10;
    s[num_digits - j - 1] = (char) digit + '0';
    }

    s[(num_digits + 1) * !p] = '';

    printf("%s%s%s\n", s, w[f], w[b << 1]);

    free(s);
    }
    }

    Posted 1st December 2012 at 2:40 am | Permalink
  26. qxcv

    Adrusi: here’s a solution without any branch statements in the compiled code* that doesn’t use gotos:

    http://pastebin.com/WkKxakpG

    (hint: function pointers)

    * Requires compilation with -O2, otherwise it ends up with a useless je instruction.

    Posted 1st December 2012 at 3:10 am | Permalink
  27. Steve,

    I’m sure it’s an honest mistake, but your Gist actually only does the FizzBuzz from 1 to 15, not from 1 to 100 ;)

    Posted 1st December 2012 at 6:45 am | Permalink
  28. @Martin May, oops thanks for pointing that out, fixed now! ;)

    Posted 1st December 2012 at 8:43 am | Permalink
  29. Ashley

    This situation reminds me of another. I am an engineer, and in college my roommate was an English major. She took a class in non-math based physics, and I found helping her with her homework to be one of the most difficult things I’ve encountered. It’s amazing how much it makes you think about what you really know when trying to view it from a non-technical viewpoint.

    Posted 1st December 2012 at 10:06 am | Permalink
  30. Rob Wheeler

    Python one-liner:

    print “\n”.join((“fizz” * (x % 3 == 0) + “buzz” * (x % 5 == 0) or str(x)) for x in xrange(1,101))

    Posted 1st December 2012 at 7:19 pm | Permalink
  31. Reith

    Ahh.. This non-coder’s algorithm, recalls Push Down Automaton and computer science classes to me :)

    Posted 1st December 2012 at 9:55 pm | Permalink
  32. In PHP:

    for ($i = 1; $i < 101; $i++) {
    $out = $i;
    $out = (($i % 3) == 0 && ($i % 5) == 0) ? "fizzbuzz" : (( ($i % 3) == 0) ? "fizz" : ((($i % 5) == 0) ? "buzz" : $out ));
    echo $out. "\n";
    }

    Posted 2nd December 2012 at 1:30 am | Permalink
  33. Codemaster

    Scurvy: your solution sucks – you’re not a coder!

    The logical test would never test the fizzbuzz part!

    Posted 2nd December 2012 at 2:37 am | Permalink
  34. Hey Steve!

    I’ll share a dirty secret – ever since I came across Pythonic Java I’ve secretly wanted to write something in it. Here’s my entry :-)

    https://gist.github.com/4188976

    /* Write a program that prints the numbers from 1 to 100.
    But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”.
    For numbers which are multiples of both three and five print “FizzBuzz”.

    Pythonic Java – https://gist.github.com/1725650
    */

    public class FizzBuzz {

    public static void main(String[] args) {

    for(int i=1; i<=100; i++) {
    if (i % 3 == 0 && i % 5 == 0) {
    System.out.println("FizzBuzz") ;}
    else if(i % 3 == 0) {
    System.out.println("Fizz") ;}
    else if(i % 5 == 0) {
    System.out.println("Buzz") ;}
    else {
    System.out.println(i) ;}}}}

    Posted 2nd December 2012 at 3:27 pm | Permalink
  35. Hi all (especially Ollie!)

    Clive here – Steve’s non-programmer colleague and the guy who tried FizzBuzz on the piece of paper.

    I just wanted to respond to Steve’s remark about iteration, and the fact I didn’t just produce the numbers 1 to 100, then apply the fizzes, buzzes and fizzbuzzes as appropriate.

    The exercise reminded me of some kind of in-the-round drinking game, where everyone is determining the responses one by one, as an iteration of the last number. Consequently, this shaped the way I approached the problem.
    In retrospect, I completely see that I would have been better off simply counting from 1 to 100, then translating each of the 100 numbers into how it should be displayed (Fizz, Buzz, FizzBuzz or as a number). But recreating the drinking game in my head, it made perfect sense to me that each number is determined by being an iteration of the last one. That feels to me like I count in real life.

    Posted 2nd December 2012 at 5:31 pm | Permalink
  36. No recursive solutions so far? In no particular language:

    function fizzbuzz( i, max ) {
    if ( i <= max ) {
    if ( i % 15 == 0 ) {
    print 'FizzBuzz'
    } else if ( i % 5 == 0 ) {
    print 'Buzz'
    } else if ( i % 3 == ) {
    print 'Fizz'
    } else {
    print i
    }
    fizzbuzz( i + 1, max )
    }
    }

    Just because you can. :)

    Posted 4th December 2012 at 2:59 pm | Permalink
  37. Hah – I can do that without if’s :)

    for (i=1; i<101; i++) {
    jQuery('’ + i + ”).appendTo(‘.list’);
    }
    jQuery(‘li:nth-child(3n)’).html(‘Fizz’);
    jQuery(‘li:nth-child(5n)’).html(‘Buzz’);
    jQuery(‘li:nth-child(15n)’).html(‘FizzBuzz’);

    http://jsfiddle.net/P3gZY/

    Posted 4th December 2012 at 3:25 pm | Permalink
  38. @qxcv
    > Adrusi: here’s a solution without any
    > branch statements in the compiled code*
    > that doesn’t use gotos:

    > http://pastebin.com/WkKxakpG

    > (hint: function pointers)

    > * Requires compilation with -O2, otherwise
    > it ends up with a useless je instruction.

    I like this solutions. its still tail calls and pointers to labels, which means it’s pretty much the same thing, but it avoids people yelling at you for using goto and is arguably more readable.

    Posted 5th December 2012 at 5:38 am | Permalink
  39. Darn it – I’ve just spent nearly 30 mins doing this and then I realise you’re all coders, but here’s my contribution for what it’s worth. It was harder then I thought it would be when I started – this assumes it works..?

    Posted 7th December 2012 at 4:35 pm | Permalink
  40. Surprisingly after so many years, this question is still relevant in programming.

    Posted 9th December 2012 at 7:43 am | Permalink

One Trackback

  1. By Weeknotes – 01/12/12 - NixonMcInnes on 1st December 2012 at 7:31 pm

    [...] November 2003 (1) < Previous [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

Notify me of followup comments via e-mail.
You can also subscribe without commenting.