1, 2, Fizz, 4, Buzz

  • Introduction



    In our recent effort to collect catalogues of shortest solutions for standard programming exercises, here is PPCG's first ever vanilla FizzBuzz challenge. If you wish to see other catalogue challenges, there is "Hello World!" and "Is this number a prime?".



    Challenge



    Write a program that prints the decimal numbers from 1 to 100 inclusive. 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”.



    Output



    The output will be a list of numbers (and Fizzes, Buzzes and FizzBuzzes) separated by a newline (either \n or \r\n). A trailing newline is acceptable, but a leading newline is not. Apart from your choice of newline, the output should look exactly like this:



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


    The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.



    Further Rules




    • This is not about finding the language with the shortest approach for playing FizzBuzz, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.


    • Submissions are scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score--if in doubt, please ask on Meta.


    • Nothing can be printed to STDERR.


    • Feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program generates FizzBuzz output, then congrats for paving the way for a very boring answer.



      Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.


    • If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Alphuck and ???), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.


    • Because the output is fixed, you may hardcode the output (but this may not be the shortest option).


    • You may use preexisting solutions, as long as you credit the original author of the program.


    • Standard loopholes are otherwise disallowed.




    As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.



    Catalogue





    var QUESTION_ID=58615;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=30525;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}

    body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#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="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table>




    `Nothing can be printed to STDERR.` Is this true only when running, or also when compiling (assuming that is a separate step?)

    @AShelly Only when running

    I’m not sure I like the fact that you hardcoded the 100 into the challenge. That way, a program that just generates the expected output is a valid entry, but is not interesting for this challenge. I think the challenge should expect the program to input the number of items to output.

    @Timwi While I agree that it would make it (only slightly) more interesting, I've very often seen FizzBuzz as strictly 1 to 100 (on Wikipedia and Rosetta Code, for example). If the goal is to have a "canonical" FB challenge, it makes sense.

    TI-BASIC's `Disp` outputs strings left-justified and numbers right-justified. Is that acceptable?

    @ThomasKwa Yes, I would think so

    A "vanilla fizzbuzz" sounds delicious.

    QBasic outputs numbers with a leading space. Is that acceptable? (Workaround costs 14 bytes.)

    What is that code snippet at the end of your answer? Is it automatically scrapping the page for answers?

    @DavidGrinberg Yep, it gets the answers and puts them into the leaderboard :)

    I can always add my Shakespearian reply, but since it barely counts as a "golfed code" (and SPL is nearly impossible to golf), perhaps it's best not to.

    Related: High throughput Fizz Buzz for a version of this where performance is the winning condition, not code-size.

  • Hexagony, 91 bytes



    Thanks for the bounty :)



    Wow, I would never have imagined I could beat Martin’s Hexagony solution.
    But—who would have thunk it—I got it done. After several days of failure because I neither had the Hexagony colorer nor the EsotericIDE to check my solution. I got several aspects of the specification wrong, so I produced a few wrong “solutions” just using pen and paper and a text editor.
    Well, finally I overcame my laziness and cloned both repositories, downloaded VisualStudio and compiled them. Wow, what useful tools they are! As you can see, I am far from being someone you’d call a programmer (I mean, come on! I didn’t even have VisualStudio installed, and have pretty much no clue about how to compile a program) ;)



    It still took me a while to find a working solution, and it is quite crammed and chaotic, but here it is in all its glory:



    Fizzbuzz in a size 6 hexagon:



    3}1"$.!$>)}g4_.{$'))\<$\.\[email protected]\}F\$/;z;u;<%<_>_..$>B/<>}))'%<>{>;e"-</_%;\/{}/>.\;.z;i;..>(('


    Hexagonal layout:



          3 } 1 " $ .
    ! $ > ) } g 4
    _ . { $ ' ) ) \
    < $ \ . \ . @ \ }
    F \ $ / ; z ; u ; <
    % < _ > _ . . $ > B /
    < > } ) ) ' % < > {
    > ; e " - < / _ %
    ; \ / { } / > .
    \ ; . z ; i ;
    . . > ( ( '


    And the beautiful rendition, thanks to Timwi’s Hexagony Colorer:



    Colorized Hexagony FizzBuzz solution



    So, here is a 110 seconds long GIF animation at 2 fps, showing the program flow during the first 6 numbers 1, 2, Fizz, 4, Buzz, Fizz, the first 220 ticks of the program (click on the image for the full size):



    enter image description here



    My goodness, thanks to the Natron compositing software the animation of the pointer was still tedious to create, but manageable. Saving 260 images of the memory was less amusing. Unfortunately EsotericIDE can’t do that automatically. Anyways, enjoy the animation!



    After all, once you wrap your head around the memory model and the rather counterintuitive wrapping of paths that cross the borders of the hexagon, Hexagony is not that hard to work with. But golfing it can be a pain in the butt. ;)



    It was fun!


    Very nice! :) That's what I get for forgetting to try side-length 6 myself. ;) (Would be interesting to see if my solution fits into side-length 6 more easily though.)

    @MartinBüttner I would love to see it :)

    I am less of a programmer than you, because what is Visual Studio? :P

    *Unfortunately EsotericIDE can’t do that automatically.* — Please go right ahead and file a feature suggestion, I might get around to doing that some day :)

    (oops this comes up after 6 months of last reply) You may golf off 1 byte from the end of the program by shifting the grey path by 1 byte and placing a "Cancelling op" in the orange path like `3}1"$.!$>)}g4_'{$))}\<$\.\[email protected]\;F\$/;z;u;<%<_>_..$>B/<>}))'%<>{>;e"-.\)(z;i;..>('`.Now there is an extra ( after the z, which can be "cancelled" with a ) or by putting the z there. Now it is a ) which pushes all commands on the orange path 1 tick later, and got back with the no-op that was on line 3. Btw I also installed Visual Studio just due to Hexagony Colorer and Esoteric IDE :P

  • Python 2, 56 bytes



    i=0;exec"print i%3/2*'Fizz'+i%5/4*'Buzz'or-~i;i+=1;"*100

    Try it online!


    Dang, that's bloody genius. Can I steal your idea to multiply the string by the mod-result?

    @TimmyD Go ahead.

    A different method for 56 (from here): `i=1;exec"print'FizzBuzz'[i%-3&4:12&8-i%5]or i;i+=1;"*100`. Anyone want to brute force search expressions to try to optimize the bit bashing?

    @ETHproductions It does.

    May I also steal your mod trick for a Ruby answer?

    Very nice technique, I love the division of the modulo result to make it binary! I have an *improvement* to get your method down to 54 chars... Of course I wouldn't post it as an answer without your permission (since it's ~95% your answer) ;)

    @Tersosauros Go ahead... my method is not very hard to find and has no doubt been independently discovered by many people.

    @MickyT What? That's 91 bytes long and not even valid, as it would only work in a REPL.

    My closest was 169 bytes: `for x in range(1,101):m={0:'Fizz'}.get(x%3,'')+{0:'Buzz'}.get(x%5,'');print(m if m else x)`

    Total genius. The use of modulo to convert to binary. Still wrapping my brain around the solution. Awesome work.

    It also works and comes out to 56 without the exec magic and the multiplied string, using a normal loop instead: `for i in range(100):print i%3/2*'Fizz'+i%5/4*'Buzz'or-~i`.

    Can someone please explain how this actually works?

  • Labyrinth, 94 bytes



    "):_1
    \ } 01/3%70.105
    " : @ " .
    " =";_""..:221
    + _
    "! 5%66.117
    _:= " .
    ="*{"..:221


    Sub-100! This was a fun one.



    Explanation



    Let's start with a brief primer on Labyrinth – feel free to skip this if you're already familiar with the basics:




    • Labyrinth has two stacks – a main stack and an auxiliary stack. Both stacks have an infinite number of zeroes at the bottom, e.g. + on an empty stack adds two zeroes, thus pushing zero.


    • Control flow in Labyrinth is decided by junctions, which look at the top of the stack to determine where to go next. Negative means turn left, zero means go straight ahead and positive means turn right... but if we hit a wall then we reverse direction. For example, if only straight ahead and turn left are possible but the top of the stack is positive, then since we can't turn right we turn left instead.


    • Digits in Labyrinth pop x and push 10*x + <digit>, which makes it easy to build up large numbers. However, this means that we need an instruction to push 0 in order to start a new number, which is _ in Labyrinth.




    Now let's get to the actual code!



    enter image description here



    Red



    Execution starts from the " in the top-left corner, which is a NOP. Next is ), which increments the top of the stack, pushing 1 on the first pass and incrementing n on every following pass.



    Next we duplicate n with :. Since n is positive, we turn right, executing } (shift top of main stack to auxiliary) and :. We hit a dead end, so we turn around and execute } and : once more, leaving the stacks like



    Main [ n n | n n ] Aux


    Once again, n is positive and we turn right, executing _101/ which divides n by 101. If n is 101 then n/101 = 1 and we turn into the @, which terminates the program. Otherwise, our current situation is



    Main [ n 0 | n n ] Aux


    Orange 1 (mod 3)



    3 turns the top zero into a 3 (10*0 + 3 = 3) and % performs a modulo. If n%3 is positive, we turn right into the yellow ". Otherwise we perform 70.105.122:.., which outputs Fizz. Note that we don't need to push new zeroes with _ since n%3 was zero in this case, so we can exploit the infinite zeroes at the bottom of the stack. Both paths meet up again at light blue.



    Light blue



    The top of the stack is currently n%3, which could be positive, so the _; just pushes a zero and immediately pops it to make sure we go straight ahead, instead of turning into the @. We then use = to swap the tops of the main and auxiliary stacks, giving:



    Main [ n | n%3 n ] Aux


    Orange 2 (mod 5)



    This is a similar situation to before, except that 66.117.122:.. outputs Buzz if n%5 is zero.



    Dark blue



    The previous section leaves the stacks like



    Main [ n%5 | n%3 n ] Aux


    { shifts the n%3 back to the main stack and * multiplies the two modulos.



    If either modulo is zero, the product is zero so we go straight into yellow. = swaps the top of the stacks and _ pushes a zero to make sure we go straight ahead, giving



    Main [ n 0 | 0 ] Aux


    Otherwise, if both modulos are nonzero, then the product is nonzero and we turn right into green. = swaps the tops of the stacks, giving



    Main [ n | (n%5)*(n%3) ] Aux


    after which we use : to duplicate n, turn right, then use ! to output n.



    Purple



    At this point, the main stack has either one or two items, depending on which path was taken. We need to get rid of the zero from the yellow path, and to do that we use +, which performs n + 0 in some order for both cases. Finally, \ outputs a newline and we're back at the start.



    Each iteration pushes an extra (n%5)*(n%3) to the auxiliary stack, but otherwise we do the same thing all over again.


    Loving the explanation.

  • Perl 5, 49 bytes



    46 bytes script + 3 bytes -E"..."



    Using say (which requires -E"...") can reduce this further to 46 bytes since say automatically includes a newline (Thanks @Dennis!):



    say'Fizz'x!($_%3).Buzz x!($_%5)||$_ for 1..100





    Perl 5, 50 bytes



    print'Fizz'x!($_%3).Buzz x!($_%5)||$_,$/for 1..100

    You can save a few bytes by using `say`.

    You broke the scoreboard...

    @LegionMammal978 Yes. Yes I did... I'll try and re-word the title then! Argh!

    Isn't `-E"..."` 8 bytes? Space + Dash + Option + Argument (+ Quoting).

    @EriktheGolfer so since I posted this, the consensus is that `-E` is 0 bytes, but since primo's answer was scored excluding the quotes, I opted to make it fair and include the quotes in mine and +1 for `-E`. The reason it's accepted as free is Perl is usually run via `perl -e` and `perl -E` is no more bytes (I thought `-M5.010` or `use 5.010` can be free as well, but perhaps not re-reading the meta post). When adding `-p` or `-n` this is counted as +1 as you would run with `perl -pe`. Hope that helps! Meta reference: http://meta.codegolf.stackexchange.com/a/7539

  • Ruby, 50 bytes



    Requires version 1.8, which seems to be popular among golfers:



    1.upto(?d){|n|puts'FizzBuzz
    '[i=n**4%-15,i+13]||n}


    In modern Ruby, you replace ?d with 100 for a 51-byte solution.



    This seems to be the world record.


    That is diabolical, love it.

    `?d` is just `100`. The `FizzBuzz` string has a newline in it, this is valid in Ruby. `string[i, s]` is a slice, starting at character `i` (0-indexed), going on for `s` characters, ignoring indices pointing outside the string. If the argument to `puts` already has a newline, it is chopped off. The formula should be simple to read? It does all the work here. I wouldn't've found it without the help of some really pro Ruby golfers.

    side note: if you were allowed to add 0 at the beginning of input(you're not), 2 bytes could be saved by using `?e.times` instead.

    Can you explain the `[i=n**4%-15,i+13]` part please? Can't seem to wrap my head around it

    @Piccolo Does **this snippet** help? If `i==-14` the slice is out of bounds so we get `nil`. If `i==-9` we slice `i+13==4` characters starting from the 9th character from the end, so `'Fizz'`. If `i==-5` we slice 8 characters starting from the 5th character from the end, so `'Buzz\n'`. (We try to slice 8 but there are only 5, so we get 5.) Et cetera.

    @Lynn Oh, that's really neat! Thank you!

    With Ruby 2.7, a 50-character solution is once again possible: `1.upto(100){puts'FizzBuzz\n'[n=_1**4%-15,n+13]||_1}`

  • gs2, 1



    f


    A quote from Mauris, the creator of gs2:




    I wanted to one-up goruby's 1-byte Hello, world!, so... This prints "1\n2\nFizz\n4\nBuzz\n...". :)




    Update: Added 27-byte answer that doesn't use f.


  • Java, 130 bytes


    This is for recent Java versions (7+). In older ones you can shave some more off using the enum trick, but I don't think the logic gets any shorter than this (86 inside main).


    class F{public static void main(String[]a){for(int i=0;i++<100;)System.out.println((i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":i));}}

    I don't think the initializer block trick helps here, since the question specifies empty stderr.

    Hmm. I know the static trick prints to stderr, but I thought enum ran cleanly. Good to know :)

    @Geobits I have created a Processing answer based of your Java answer.

    beat me by 14 bytes! Using <1 instead of ==0 is a great way to save!

    `class F{public static` -> `interface F{static` in java 8

    That's not _quite_ how enums work. You would have to do `enum F{;public...`, so you wouldn't actually be saving any bytes.

    But great job! +1

    @HyperNeutrino The enum trick works if you add `System.exit(0);` at the end. Total length: 112 bytes. `enum F{F;{for(int i=0;i++<100;)System.out.println((i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":i));System.exit(0);}}`. See my "Hello World" answer for details.

    An interesting trick: The closing bracket in `i++<100;)` can also be moved to the other closing brackets near the end and it works the same (with the same byte count). But then you have one less smiley in your code. :(

  • Pyth, 30


    VS100|+*!%N3"Fizz"*!%N5"Buzz"N

    Try it here


    Explanation:


    VS100|+*!%N3"Fizz"*!%N5"Buzz"N
    VS100 : for N in range(1,101)
    | : logical short-circuiting or
    +*!%N3"Fizz" : add "Fizz" * not(N % 3)
    : Since not gives True/False this is either "" or "Fizz"
    *!%N5"Buzz" : Same but with 5 and Buzz
    N : Otherwise N
    : The output of the | is implicitly printed with a newline

  • Retina, 317 139 134 132 70 63 60 55 bytes



    .100{`^
    _
    *\(a`(___)+
    Fi;$&
    \b(_{5})+$
    Bu;
    ;_*
    zz
    '_&`.


    Try it online!



    Explanation



    .100{`^
    _


    The . is the global silent flag which turns off implicit output at the end of the program. 100{ wraps the rest of the program in a loop which is executed for 100 iterations. Finally, the stage itself just inserts a _ at the beginning of the string, which effectively increments a unary loop counter.



    *\(a`(___)+
    Fi;$&


    More configuration. *\( wraps the remainder of the program in a group, prints its result with a trailing linefeed, but also puts the entire group in a dry run, which means that its result will be discarded after printing, so that our loop counter isn't actually modified. a is a custom regex modifier which anchors the regex to the entire string (which saves a byte on using ^ and $ explicitly).



    The atomic stage itself takes care of Fizz. Divisibility by 3 can easily be checked in unary: just test if the number can be written as a repetition of ___. If this is the case, we prepend Fi; to the string. The semicolon is so that there is still a word boundary in front of the number for the next stage. If we turned the line into Fizz___... the position between z and _ would not be considered a boundary, because regex treats both letters and underscores as word characters. However, the semicolon also allows us to remove the zz duplication from Fizz and Buzz.



    \b(_{5})+$
    Bu;


    We do the exact same for divisibility by 5 and Bu;, although we don't need to keep the _s around this time. So we would get a results like



    _
    __
    Fi;___
    ____
    Bu;
    Fi;______
    ...
    Fi;Bu;
    ...


    This makes it very easy to get rid of the underscores only in those lines which contain Fizz, while also filling in the zzs:



    ;_*
    zz


    That is, we turn each semicolon into zz but we also consume all the _s right after it. At this point we're done with FizzBuzz in unary. But the challenge wants decimal output.



    '_&`.


    & indicates a conditional: this stage is only executed if the string contains an underscore. Therefore, Fizz, Buzz and FizzBuzz iterations are left untouched. In all other iterations (i.e. those which are neither divisible by 3 nor 5), we just count the number of characters, converting the result to decimal.


  • beeswax, 104 89 81 bytes


    Denser packing allowed for cutting off 8 more bytes.


    Shortest solution (81 bytes), same program flow, different packing.


    [email protected]<
    p?{@b'gA<
    [email protected]`zzuB`d'%[email protected]<f`z`<
    >~P"#"_"1F3~%'d`Fiz`b
    d;"[email protected]~.<
    >[email protected]~0+d

    Changing the concept enabled me to cut down the code by 15 bytes.
    I wanted to get rid of the double mod 5 test in the solution, so I implemented a flag.


    Short explanation:


    if n%3=0 Fizz gets printed, and the flag gets set. The flag is realized simply by pushing the top lstack value onto the gstack (instruction f).


    If n%5=0, then either n%3=0(FizzBuzz case) or n%3>0(Buzz case). In both cases, Buzz gets printed, and the flag reset by popping the stack until it’s empty (instruction ?).


    Now the interesting cases:


    If n%5>0, then either we had n%3=0 (printing Fizz case, n must not be printed) or n%3>0 (Fizz was not printed, so n has to be printed). Time to check the flag. This is realized by pushing the length of gstack on top of gstack (instruction A).
    If n%3 was 0 then the gstack length is >0.
    If n%3 was >0, the gstack length is 0.
    A simple conditional jump makes sure n gets only printed if the length of gstack was 0.


    Again, after printing any of n, Fizz, and/or Buzz and the newline, the gstack gets popped twice to make sure it’s empty. gstack is either empty [], which leads to [0] after instruction A (push length of gstack on gstack), or it contains one zero ([0],the result of n%3), which leads to [0 1], as [0] has the length 1. Popping from an empty stack does not change the stack, so it’s safe to pop twice.


    If you look closer you can see that, in principle, I folded


    >      q
    d`Fizz`f>

    into


    <f`z`<
    d`Fiz`b

    which helps to get rid of the all the wasted space between A and < at the end of the following row in the older solution below:


    q?{@b'gA<       p      <

    New concept solution (89 bytes) including animated explanation:


    [email protected] <
    q?{@b'gA< p <
    p?<@`zzuB`b'%[email protected]<f`zziF`b'<
    >[email protected][email protected]~-";~P"#"_"1F3~%d

    Hexagonal layout:


       q ? @   <
    q ? { @ b ' g A < p <
    p ? < @ ` z z u B ` b ' % ~ 5 F @ < f ` z z i F ` b ' <
    > N @ 9 P ~ 0 + . ~ @ ~ - " ; ~ P " # " _ " 1 F 3 ~ % d



    Animation of the first 326 ticks at 2 fps, with local and global stacks, and output to STDOUT.


    beeswax FizzBuzz animation




    For comparison, below are the path overlays of the older, more complex solution. Maybe it’s also the prettier solution, from a visual standpoint ;)


    Program with path overlay


    This is as crazy and beautiful as Hexagony. Have a +1!

    @ETHproductions I still need to give Hexagony a try, but from what I can tell from the language specs, my beeswax doesn’t even come close to the craziness of Hexagony.

    How are you making those animations?

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM