200
\$\begingroup\$

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>

\$\endgroup\$
14
  • 1
    \$\begingroup\$ Nothing can be printed to STDERR. Is this true only when running, or also when compiling (assuming that is a separate step?) \$\endgroup\$
    – AShelly
    Commented Sep 24, 2015 at 20:47
  • 1
    \$\begingroup\$ @AShelly Only when running \$\endgroup\$
    – Beta Decay
    Commented Sep 24, 2015 at 20:48
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Timwi
    Commented Sep 24, 2015 at 23:28
  • 9
    \$\begingroup\$ @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. \$\endgroup\$
    – Geobits
    Commented Sep 25, 2015 at 0:50
  • 77
    \$\begingroup\$ A "vanilla fizzbuzz" sounds delicious. \$\endgroup\$ Commented Sep 25, 2015 at 15:12

426 Answers 426

1
2 3 4 5
15
113
+100
\$\begingroup\$

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_.{$'))\<$\.\.@\}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!

\$\endgroup\$
5
  • 1
    \$\begingroup\$ 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.) \$\endgroup\$ Commented Mar 6, 2016 at 9:45
  • \$\begingroup\$ @MartinBüttner I would love to see it :) \$\endgroup\$
    – M L
    Commented Mar 6, 2016 at 16:56
  • 2
    \$\begingroup\$ I am less of a programmer than you, because what is Visual Studio? :P \$\endgroup\$
    – Riker
    Commented Mar 10, 2016 at 2:42
  • 5
    \$\begingroup\$ 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 :) \$\endgroup\$
    – Timwi
    Commented Mar 10, 2016 at 13:22
  • 2
    \$\begingroup\$ (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_'{$))}\<$\.\.@\;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 \$\endgroup\$
    – Sunny Pun
    Commented Oct 14, 2016 at 3:50
99
\$\begingroup\$

Python 2, 56 bytes

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

Try it online!

\$\endgroup\$
12
  • 12
    \$\begingroup\$ Dang, that's bloody genius. Can I steal your idea to multiply the string by the mod-result? \$\endgroup\$ Commented Sep 24, 2015 at 20:01
  • 1
    \$\begingroup\$ @TimmyD Go ahead. \$\endgroup\$
    – feersum
    Commented Sep 24, 2015 at 20:06
  • 26
    \$\begingroup\$ 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? \$\endgroup\$
    – xnor
    Commented Sep 25, 2015 at 5:35
  • 2
    \$\begingroup\$ @Tersosauros Go ahead... my method is not very hard to find and has no doubt been independently discovered by many people. \$\endgroup\$
    – feersum
    Commented Mar 6, 2016 at 21:16
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – jaaq
    Commented Jan 20, 2021 at 8:38
53
\$\begingroup\$

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.

\$\endgroup\$
1
  • 11
    \$\begingroup\$ Loving the explanation. \$\endgroup\$ Commented Sep 27, 2015 at 23:08
39
\$\begingroup\$

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.

\$\endgroup\$
8
  • 1
    \$\begingroup\$ That is diabolical, love it. \$\endgroup\$ Commented Sep 28, 2015 at 1:13
  • 1
    \$\begingroup\$ ?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. \$\endgroup\$
    – lynn
    Commented Sep 30, 2015 at 21:34
  • \$\begingroup\$ 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. \$\endgroup\$
    – Shelvacu
    Commented Nov 12, 2015 at 6:11
  • 4
    \$\begingroup\$ @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. \$\endgroup\$
    – lynn
    Commented Aug 4, 2018 at 23:15
  • 5
    \$\begingroup\$ 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} \$\endgroup\$
    – Nnnes
    Commented Mar 3, 2020 at 18:29
33
\$\begingroup\$

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.

\$\endgroup\$
33
\$\begingroup\$

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
\$\endgroup\$
5
  • \$\begingroup\$ You can save a few bytes by using say. \$\endgroup\$
    – Dennis
    Commented Sep 25, 2015 at 6:15
  • \$\begingroup\$ You broke the scoreboard... \$\endgroup\$ Commented Sep 27, 2015 at 12:10
  • \$\begingroup\$ @LegionMammal978 Yes. Yes I did... I'll try and re-word the title then! Argh! \$\endgroup\$ Commented Sep 27, 2015 at 12:47
  • \$\begingroup\$ Isn't -E"..." 8 bytes? Space + Dash + Option + Argument (+ Quoting). \$\endgroup\$ Commented Sep 22, 2016 at 11:00
  • 1
    \$\begingroup\$ @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: meta.codegolf.stackexchange.com/a/7539 \$\endgroup\$ Commented Sep 22, 2016 at 11:30
31
\$\begingroup\$

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));}}
\$\endgroup\$
8
  • \$\begingroup\$ I don't think the initializer block trick helps here, since the question specifies empty stderr. \$\endgroup\$
    – feersum
    Commented Sep 24, 2015 at 19:47
  • 6
    \$\begingroup\$ beat me by 14 bytes! Using <1 instead of ==0 is a great way to save! \$\endgroup\$
    – ESP
    Commented Nov 8, 2015 at 18:25
  • 4
    \$\begingroup\$ class F{public static -> interface F{static in java 8 \$\endgroup\$ Commented Nov 28, 2015 at 15:53
  • 2
    \$\begingroup\$ That's not quite how enums work. You would have to do enum F{;public..., so you wouldn't actually be saving any bytes. \$\endgroup\$
    – hyperneutrino
    Commented Mar 7, 2016 at 2:56
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Nov 23, 2017 at 17:48
29
\$\begingroup\$

ArnoldC, 842 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE a
YOU SET US UP 100
HEY CHRISTMAS TREE b
YOU SET US UP 0
HEY CHRISTMAS TREE r
YOU SET US UP 0
STICK AROUND a
GET TO THE CHOPPER b
HERE IS MY INVITATION 101
GET DOWN a
ENOUGH TALK
GET TO THE CHOPPER r
HERE IS MY INVITATION b
I LET HIM GO 15
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE r
GET TO THE CHOPPER r
HERE IS MY INVITATION b
I LET HIM GO 3
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE r
GET TO THE CHOPPER r
HERE IS MY INVITATION b
I LET HIM GO 5
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE r
TALK TO THE HAND b
BULLSHIT
TALK TO THE HAND "Buzz"
YOU HAVE NO RESPECT FOR LOGIC
BULLSHIT
TALK TO THE HAND "Fizz"
YOU HAVE NO RESPECT FOR LOGIC
BULLSHIT
TALK TO THE HAND "FizzBuzz"
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET DOWN 1
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

First try at golfing, I think this is as bad as it gets (both language and golfing).

\$\endgroup\$
2
  • 5
    \$\begingroup\$ YOU HAVE NO RESPECT FOR LOGIC lol, this is a great language ;) \$\endgroup\$ Commented Mar 10, 2016 at 17:39
  • 2
    \$\begingroup\$ Hahahaha!!! You should've made it a method, worse bytecount, better phrases ;). \$\endgroup\$ Commented Oct 13, 2016 at 17:46
28
+500
\$\begingroup\$

Apple Shortcuts, 9 actions

enter image description here

This creates a loop that runs 100 times. For each loop, it gets the iteration number and modulos it by 3. We then take the result and use regex replacement to change it to “Fizz” if it is 0. Then, we take the iteration number and use regex replacement to change it to “Buzz” if it ends in 0 or 5.

At this point, we have a value that is either “Fizz” or a number, and we have a value that is either “Buzz” or a number. We combine those two values together into a single string, and use regex replacement to remove any numbers. This leaves us with one of “Fizz”, “Buzz”, “FizzBuzz”, or an empty string. Finally, we use one more regex replacement to replace an empty string with the iteration number.

The final value left at the end of each iteration is added to the repeat results, so after the loop has finished running, we simply print the list of repeat results with a “show result” action, which automatically formats the list as a bunch of newline separated values.

For those who don’t want to/don’t know how to enter this code, here’s an iOS link that should hopefully maybe possibly work.

\$\endgroup\$
26
\$\begingroup\$

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
\$\endgroup\$
26
\$\begingroup\$

JavaScript, 62 bytes

for(i=0;++i<101;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz'

I think I this is the shortest Javascript solution now.

\$\endgroup\$
5
  • 2
    \$\begingroup\$ Wow, just wow! But all the other JS answers use console.log; it's much less annoying than having to press "OK" on 100 pop-up boxes in a row. Could you please change this? It'll only be 62 bytes, still three better than mine. \$\endgroup\$ Commented Nov 15, 2015 at 3:04
  • \$\begingroup\$ I'll have to do so tomorrow, as I have already edited 5 of my own posts and can't edit anymore... \$\endgroup\$ Commented Nov 15, 2015 at 5:16
  • 2
    \$\begingroup\$ Oh, I didn't realise there was a limit to editing... \$\endgroup\$ Commented Nov 15, 2015 at 18:48
  • \$\begingroup\$ So if I found a shorter answer that's similar to this, do I edit this or post a new answer? (it still uses console.log) \$\endgroup\$ Commented Oct 26, 2020 at 2:44
  • \$\begingroup\$ [...Array(99)].map((e,i)=>(((++i)%3?'':'Fizz')+((i)%5?'':'Buzz'))||i) \$\endgroup\$
    – zsitro
    Commented Jan 21, 2022 at 19:00
26
+500
\$\begingroup\$

brainfuck, 206 bytes

++>+++++>>>>>++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>]>
[+[[<<]<[>>]+++<[<.<.<..[>]]<<-[>>>[,>>[<]>[--.++<<]>]]+++++<[+[-----.++++<<]>>+
..<-[>]]<[->>,>+>>>->->.>]<<]<[>+<<<,<->>>+]<]

Formatted:

++>+++++>>>>>
++++++++++[>+>>+>>+>+<<<[++++<-<]<,<,-<-<++<++++[<++>++++++>]++>>]
>
[
  +
  [
    [<<]
    <[>>]
    +++<
    [
      Fizz
      <.<.<..
      [>]
    ]
    <<-
    [
      >>>
      [
        ,>>[<]
        >[--.++<<]
        >
      ]
    ]
    +++++<
    [
      Buzz
      +[-----.++++<<]
      >>+..
      <-
      [>]
    ]
    <[->>,>+>>>->->.>]
    <<
  ]
  <[>+< <<,<->>>+]
  <
]

Try it online

The memory layout is

0 a 122 105 70 b f 0 t d1 s d2 c d 10 0

where f cycles by 3, b cycles by 5, d1 is ones digit, d2 is tens digit, s is a flag for whether to print tens digit, d cycles by 10, c is copy space for d, t is working space that holds 0 or junk data or a flag for not-divisible-by-3, and a determines program termination by offsetting the pointer after Buzz has been printed 20 times.

\$\endgroup\$
1
  • \$\begingroup\$ For some reason on code.golf this code bugs :/ \$\endgroup\$
    – DialFrost
    Commented Nov 21, 2022 at 3:00
25
\$\begingroup\$

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.

\$\endgroup\$
24
\$\begingroup\$

Perl 5, 45 bytes

say((Fizz)[$_%3].(Buzz)[$_%5]or$_)for+1..100

Requires the -E option, counted as one. This must be run from the command line, i.e.:

perl -Esay((Fizz)[$_%3].(Buzz)[$_%5]or$_)for+1..100

Quotes around the command are unnecessary, if one avoids using spaces, or any other characters which can act as command line separators (|, <, >, &, etc.).


Perl 5, 48 bytes

print+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..100

If command line options are counted as one each, -l would save one byte (by replacing $/). By Classic Perlgolf Rules, however, this would count 3: one for the -, one for the l, and one for the necessary space.

\$\endgroup\$
3
  • \$\begingroup\$ You can use say, with the -E switch, which has edit distance 1 to -e, so it should count as 1 byte. \$\endgroup\$
    – Dennis
    Commented Sep 25, 2015 at 6:24
  • \$\begingroup\$ Hey primo, I feel like I'm cheating in my answer for using say, I've assumed that -E can be used in place of -e which would bring you down to 44 rather than 46. I don't think it's fair that I'm scoring differently to you, what's the preferred scoring mechanism? I generally use print to avoid this! Closest to a consensus would be this? \$\endgroup\$ Commented Sep 25, 2015 at 16:15
  • \$\begingroup\$ My personal take is that every additional byte on the command line should score 1. In particular for say, if your code can be written on one line avoiding any OS separators, score 1 for -E. If you need to use quotes, e.g. -E"$a||$b", score 3. If you can't get it on one line, score 5 for -M5.01. But at that point you'd probably be better off using -l. I don't agree that it should be free by default, for two reasons: 1) the improvement is trivial and uninteresting, and 2) there is no version of the interpreter for which it is enabled by default. \$\endgroup\$
    – primo
    Commented Sep 25, 2015 at 16:39
24
\$\begingroup\$

beeswax, 104 89 81 bytes

Denser packing allowed for cutting off 8 more bytes.

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

p?@<
p?{@b'gA<
p@`zzuB`d'%~5F@<f`z`<
 >~P"#"_"1F3~%'d`Fiz`b
 d;"-~@~.<
>?N@9P~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:

q?@ <
 q?{@b'gA<       p      <
p?<@`zzuB`b'%~5F@<f`zziF`b'<
>N@9P~0+.~@~-";~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

\$\endgroup\$
4
  • 4
    \$\begingroup\$ This is as crazy and beautiful as Hexagony. Have a +1! \$\endgroup\$ Commented Feb 26, 2016 at 17:08
  • \$\begingroup\$ @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. \$\endgroup\$
    – M L
    Commented Feb 26, 2016 at 17:17
  • \$\begingroup\$ Let us continue this discussion in chat. \$\endgroup\$
    – M L
    Commented Dec 3, 2016 at 20:53
  • \$\begingroup\$ How are you making those animations? \$\endgroup\$ Commented Aug 19, 2018 at 3:32
24
+850
\$\begingroup\$

Vyxal, j, 65 bits1, 18 17 14 12 11 8.125 bytes

₁ƛ₍₃₅kF½*∑∴

Try it Online! (link is to bitstring)

I refuse to be beaten by Arn, Ash and Fig. I absolutely will not be beaten by any of those languages. Vyxal forever lads.

And yes, that really is 8.125 bytes. We have a fractional byte encoding system now. The 65-bit bitstring can be found at the online link.

The program is presented as SBCS for convenience.

Explained

₁ƛ₍₃₅kF½*∑∴
₁           # Push 100 to the stack
 ƛ          # Over the range [1, 100], map: (we'll call the argument n)
  ₍₃₅       #   [n % 3 == 0, n % 5 == 0] (call this X)
     kF     #   "FizzBuzz"
       ½    #   ["Fizz", "Buzz"] # halve the string - split into two equal pieces
        *∑  #   sum(X * ↑)
          ∴ #   max(↑, n)
            # The -j flag joins on newlines before outputting

If you want it flagless:

Vyxal, 12 bytes

₁⟑₍₃₅kF½*∑∴,

Try it Online!

See how inconsequential flags are?

Vyxal, 17 bytes

₁⟑35fḊ`₴ḟȦ↑`½*∑∴,

No questionable built-ins, no flags, just plain legitimate fizzbuzz.

Try it Online!

\$\endgroup\$
22
  • 10
    \$\begingroup\$ I don't think it counts as beating anyone if the language was designed after the challenge \$\endgroup\$
    – Luis Mendo
    Commented Aug 31, 2020 at 12:33
  • 5
    \$\begingroup\$ There's a debate to be had about whether it means anything for an answer to beat or be beaten by an answer in a different language, but the age of the language should be irrelevant in that determination. \$\endgroup\$ Commented Sep 2, 2020 at 2:59
  • 16
    \$\begingroup\$ I see. Well... I know how meta counts flags, but I'm not sure how sportsmanlike it is to compare your language (and say you "legitimately beat Dennis") to Jelly, which has no such flags, without counting the flags. You're basically tucking an implicit "increment" and "join by NL" instruction into the program flags, and then counting two fewer bytes. \$\endgroup\$
    – lynn
    Commented Sep 30, 2020 at 13:37
  • 5
    \$\begingroup\$ Plus the fact you have so many FizzBuzz builtins... one for "is this a Fizz number", one for "is this a Buzz number" and of course a (two-byte) builtin for "FizzBuzz" itself. Without those you'd be over 20 bytes for sure. \$\endgroup\$
    – Neil
    Commented May 1, 2021 at 0:45
  • 5
    \$\begingroup\$ Sorry, still using FizzBuzz builtins. \$\endgroup\$
    – Neil
    Commented May 1, 2021 at 7:37
23
\$\begingroup\$

><>, 68 66 65 64 63 bytes

1\2+2fooo o"Buzz"<
o>:::3%:?!\$5%:?!/*?n1+:aa*)?;a
o.!o"Fizz"/o

The only trick is to multiply remainders as a condition to number printing. That way, if one of them is 0 we won't print the number.

You can try it here.

Saved one byte thanks to Sp3000, another thanks to randomra, and a last one thanks to Jacklyn. Thanks a lot!

\$\endgroup\$
9
  • 1
    \$\begingroup\$ Very well golfed, I love the reuse of the "\" on the first line and the one on the second line. \$\endgroup\$
    – cole
    Commented Sep 25, 2015 at 22:59
  • 1
    \$\begingroup\$ -1 byte if you move the o at end of the second line to the empty space at the start of the line, I believe. \$\endgroup\$
    – Sp3000
    Commented Sep 26, 2015 at 0:55
  • \$\begingroup\$ @Sp3000 Indeed, I spent so much time golfing this I don't know how this did not come to mind \$\endgroup\$
    – Aaron
    Commented Sep 27, 2015 at 11:28
  • 1
    \$\begingroup\$ Who needs fizz buzz when you can have foooo Buzz? \$\endgroup\$ Commented Sep 4, 2017 at 20:46
  • 2
    \$\begingroup\$ @JoKing thanks, I've updated the link. Sadly not much motivation to code outside of work nowadays, but if it comes back I hope I'll remember code.golf ! \$\endgroup\$
    – Aaron
    Commented Aug 29, 2021 at 13:20
22
\$\begingroup\$

gs2, 28 27 (without f)

Hex:

1b 2f fe cc 04 46 69 7a 7a 09 07 42 75 7a 7a 19 06 27 2d d8 62 32 ec 99 dc 61 0a

Explanation:

1b    100
2f    range1 (1..n)
fe    m: (map rest of program)

cc    put0 (pop and store in register 0)
04    string-begin
Fizz
09    9
07    string-separator
Buzz
19    25
06    string-end-array (result: ["Fizz"+chr(9) "Buzz"+chr(25)])

27    right-uncons
2d    sqrt
d8    tuck0 (insert value of register 0 under top of stack)
62    divides
32    times (string multiplication)
ec    m5 (create block from previous 5 tokens, then call map)

99    flatten
dc    show0 (convert register 0 to string and push it)
61    logical-or
0a    newline

Embedding 3 and 5 into the string constant doesn't work because \x05 ends string literals.

Note: This problem can be solved in 1 byte with gs2 using the built-in f.

\$\endgroup\$
21
\$\begingroup\$

C, 74 bytes

main(i){for(;i<101;puts(i++%5?"":"Buzz"))printf(i%3?i%5?"%d":0:"Fizz",i);}

The 0 argument to printf instead of "" is fishy, but seems to work on most platforms I try it on. puts segfaults when you try the same thing, though. Without it, you get 75 bytes.

There are 73-byte solutions that work on anarchy golf, and I found one digging around in the right places on the internet, but they rely on platform-specific behavior. (As you might have guessed, it's something of the form puts("Buzz"±...).)

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Nice trick to get i=1 for the no args case (argc=1). It's a feature: you can start the sequence from any point by running ./fizzbuzz $(seq 40) :P \$\endgroup\$ Commented May 27, 2016 at 21:05
  • \$\begingroup\$ this can be trivially ported to c++ by adding the necessary boilerplate \$\endgroup\$
    – c--
    Commented Jun 6, 2022 at 23:33
  • 1
    \$\begingroup\$ it seems to segfault in TIO \$\endgroup\$
    – c--
    Commented Jun 6, 2022 at 23:35
  • \$\begingroup\$ As c-- mentioned, this segfaults on TIO \$\endgroup\$
    – DialFrost
    Commented Nov 4, 2022 at 1:49
20
\$\begingroup\$

Scratch, 203 185 bytes

Bytes counted from the golfed textual representation, per this meta post. Scratch is not very space-efficient.

say is the closest thing to a stdout Scratch has: the sprite displays a speech bubble containing whatever it is saying. In practice, a wait n secs block would be needed to actually read this output, but for the purposes of this challenge this code fulfills the requirements.

\$\endgroup\$
8
  • \$\begingroup\$ You're missing numbers after the y = (in both occurrences) \$\endgroup\$
    – Beta Decay
    Commented Oct 28, 2015 at 10:29
  • \$\begingroup\$ @BetaDecay Sorry? I don't follow. \$\endgroup\$
    – Tuesday
    Commented Oct 28, 2015 at 14:33
  • 1
    \$\begingroup\$ @BetaDecay That's the empty string. :) if you click on the image, you can view it in action! \$\endgroup\$
    – Tuesday
    Commented Oct 28, 2015 at 17:12
  • 1
    \$\begingroup\$ Nice one. I've never seen a Scratch solution before. :) \$\endgroup\$
    – hyperneutrino
    Commented Mar 7, 2016 at 3:01
  • 1
    \$\begingroup\$ Never thought Scratch solution will show up here. So awesome to see this. Great work @timothymh \$\endgroup\$
    – Joe Ferndz
    Commented Dec 26, 2020 at 5:50
20
\$\begingroup\$

Jelly, 24 20 bytes

³µ3,5ḍTị“¡Ṭ4“Ụp»ȯµ€G

Try it online!

How it works

³µ3,5ḍTị“¡Ṭ4“Ụp»ȯµ€G  Main link. No input.

³                     Yield 100.
 µ                    Begin a new, monadic chain.
                 µ€   Apply the preceding chain to all integers n in [1, ..., 100].
  3,5ḍ                Test n for divisibility by 3 and 5.
      T               Get all truthy indices.
                      This yields [1] (mult. of 3, not 5), [2] (mult. of 5, not 3),
                      [1, 2] (mult. of 15) or [].
        “¡Ṭ4“Ụp»      Yield ['Fizz', 'Buzz'] by indexing in a dictionary.
       ị              Retrieve the strings at the corr. indices.
                ȯ     Logical OR hook; replace an empty list with n.
                   G  Grid; join the list, separating by linefeeds.
\$\endgroup\$
4
  • 1
    \$\begingroup\$ again nobody out golfed dennis (except for the HQ9+ style answer) \$\endgroup\$ Commented Jul 17, 2016 at 17:08
  • \$\begingroup\$ @noɥʇʎԀʎzɐɹƆ but now they have. \$\endgroup\$
    – lyxal
    Commented Aug 31, 2020 at 4:08
  • 3
    \$\begingroup\$ µ€ is now known as ), saving a byte. \$\endgroup\$
    – lynn
    Commented Sep 30, 2020 at 10:17
  • 3
    \$\begingroup\$ @Lyxal It seems that you're right... ^ Lynn has out golfed Dennis in the comment above. \$\endgroup\$
    – user99151
    Commented Nov 16, 2020 at 9:21
19
\$\begingroup\$

C, 85 bytes

i;main(){for(;i++<=99;printf("%s%s%.d\n",i%3?"":"Fizz",i%5?"":"Buzz",(i%3&&i%5)*i));}

-2 thanks to squeamish.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ Global variables are initialized to zero, so instead of main(i), try i;main(). Then you can get rid of the i-- at the start of the for() loop. You don't need the line break either. That should bring the byte count down to 85. \$\endgroup\$
    – r3mainer
    Commented Sep 24, 2015 at 22:36
  • \$\begingroup\$ Found a way to shave one more byte: main(i){for(;printf("%s%s%.d\n",i%3?"":"Fizz",i%5?"":"Buzz",(i%3&&i%5)*i),99/i++;);} \$\endgroup\$
    – Tob Ernack
    Commented Sep 25, 2015 at 4:48
  • 2
    \$\begingroup\$ printf(i%5?i%3?"%d\n":"Fizz\n":i%3?"Buzz\n":"FizzBuzz\n",i) saves another byte, can be combined with @TobErnack's comment. \$\endgroup\$
    – hvd
    Commented Sep 26, 2015 at 16:58
  • 3
    \$\begingroup\$ Depending on how UB you want to get, you can do 73, 74, or 75 bytes. Here's my 74 byte answer. \$\endgroup\$
    – lynn
    Commented Sep 27, 2015 at 16:44
  • 3
    \$\begingroup\$ OMG I spent maybe 3 hours trying to get this thing just one byte smaller. Here you go. Replace (i%3&&i%5)*i with i%3*i%5?i:0 I'm going to bed \$\endgroup\$ Commented Sep 30, 2015 at 10:24
19
\$\begingroup\$

Haskell, 84 82 bytes

main=mapM putStrLn[show n`max`map("FizzBuzz"!!)[6-2*gcd 3n..2+gcd 5n]|n<-[1..100]]

The expressions work out like this:

 n   6-2*gcd(3,n)  2+gcd(5,n)
=============================
 1        4             3   
 2        4             3   
 3       *0             3   
 4        4             3   
 5        4            *7   
 6       *0             3   
 7        4             3   
 8        4             3   
 9       *0             3   
10        4            *7    
11        4             3    
12       *0             3    
13        4             3    
14        4             3    
15       *0            *7    
16       ...           ...

We use them as start and end points for slicing the string. For example, when n == 5, then map("FizzBuzz"!!)[4..7] == "Buzz".

For non-divisible numbers, the range [4..3] is empty, so the result of map is "", and max (show n) replaces that result.

Old 84 byte answer

main=mapM f[1..100]
f n|d<-drop.(*4).mod n=putStrLn$max(show n)$d 3"Fizz"++d 5"Buzz"

d = drop.(*4).mod n is key here: d 3 "Fizz" is drop (n`mod`3 * 4) "Fizz". This is "Fizz" when n `mod` 3 is 0 and "" otherwise.

Other stuff

I got here via this 85:

main=mapM putStrLn[max(show n)$drop(6-2*gcd 3n)$take(3+gcd 5n)"FizzBuzz"|n<-[1..100]]

Here is another interesting 85:

f n=cycle[show n,"Fizz","Buzz",f 3++f 5]!!div(gcd 15n)2
main=mapM(putStrLn.f)[1..100]

The world record is 80 bytes by henkma.

\$\endgroup\$
9
  • \$\begingroup\$ Rearrangement golfs it down to 82, I think: (%)=drop.(*4).mod n;main=mapM putStrLn[max(show n)$3%"Fizz"++5%"Buzz"|n<-[0..100]]. \$\endgroup\$
    – CR Drost
    Commented Sep 27, 2015 at 16:35
  • \$\begingroup\$ Wait, then n isn't in scope. Hm. \$\endgroup\$
    – CR Drost
    Commented Sep 27, 2015 at 16:38
  • \$\begingroup\$ Yeah, that doesn't work, but I've hit an alternative 85-byte solution that looks a lot like it: main=mapM putStrLn[max(show n)$3%"Fizz"++5%"Buzz"|n<-[0..100],(%)<-[drop.(*4).mod n]] \$\endgroup\$
    – lynn
    Commented Sep 28, 2015 at 22:47
  • 1
    \$\begingroup\$ I suggest you reconsider your quest for readable code on a code golf website :) \$\endgroup\$
    – lynn
    Commented Feb 28, 2019 at 22:25
  • 1
    \$\begingroup\$ @dfeuer I found a shorter solution, so you can fix your downvote if you'd like. \$\endgroup\$
    – lynn
    Commented Sep 29, 2020 at 22:20
17
\$\begingroup\$

CJam, 35 bytes

100{)_[Z5]f%:!"FizzBuzz"4/.*s\e|N}/

Try it online in the CJam interpreter.

How it works

100{)_[Z5]f%:!"FizzBuzz"4/.*s\e|N}/
100{                             }/  For each integer I between 0 and 99:
    )_                                 Increment I and push a copy.
      [Z5]                             Push [3 5].
          f%                           Map % to push [(I+1)%3 (I+1)%5].
            :!                         Apply logical NOT to each remainder.
              "FizzBuzz"4/             Push ["Fizz" "Buzz"].
                          .*           Vectorized string repetition.
                            s\         Flatten the result and swap it with I+1.
                              e|       Logical OR; if `s' pushed an empty string,
                                       replace it with I+1.
                                N      Push a linefeed.
\$\endgroup\$
1
  • 4
    \$\begingroup\$ More straightforward solution: 100{):I3%!"Fizz"*I5%!"Buzz"*+Ie|N}/ \$\endgroup\$ Commented Sep 30, 2015 at 14:12
17
\$\begingroup\$

C#, 128 126 125 124 bytes

class A{static void Main(){for(var i=0;i++<100;)System.Console.Write("{0:#}{1:;;Fizz}{2:;;Buzz}\n",i%3*i%5>0?i:0,i%3,i%5);}}

89 bytes without the boilerplate code around.

Done with the use of C#'s conditional formatting.

With two section separators ;, Fizz or Buzz are printed if the value from their condition is zero.


Saved a total of 4 bytes thanks to @RubberDuck, @Timwi and @Riokmij.

\$\endgroup\$
10
  • \$\begingroup\$ It would be shorter to call Write and append the newline directly to the string, right? \$\endgroup\$
    – RubberDuck
    Commented Sep 24, 2015 at 23:26
  • \$\begingroup\$ It’s also one byte shorter to write i%3*i%5>0?i:0 instead of i%3*i%5==0?0:i. \$\endgroup\$
    – Timwi
    Commented Sep 24, 2015 at 23:31
  • \$\begingroup\$ You can save another byte on the for statement by using for(var i=0;i++<100;) \$\endgroup\$
    – Najkin
    Commented Sep 25, 2015 at 8:08
  • 1
    \$\begingroup\$ You can save three more bytes by leveraging String Interpolation from C#6.0 and embedding the format arguments into the string itself (e.g. $"{(i%3*i%5>0?i:0):#}...\n") \$\endgroup\$
    – LiamK
    Commented Sep 29, 2015 at 12:58
  • 3
    \$\begingroup\$ can do with 121 bytes today - class A{static void Main(){for(var i=0;i<100;)System.Console.Write($"{(++i%3*i%5<1?0:i):#}{i%3:;;Fizz}{i%5:;;Buzz}\n");}} \$\endgroup\$ Commented Oct 28, 2018 at 9:45
17
\$\begingroup\$

MUMPS, 56 54 bytes

f i=1:1:100 w:i#5=0 "Fizz" w:i#3=0 "Buzz" w:$X<3 i w !

What's this w:$X<3 i thing, you ask? $X is a magic variable (an "intrinsic") that stores the horizontal position of the output cursor (as a number of characters from the left edge of the terminal). w is the abbreviated form of the WRITE command. The syntax command:condition args is a postconditional - "if condition, then do command args".

So we're checking whether the output cursor has been advanced more than two characters (which would mean that at least one of "Fizz" or "Buzz" has been written to the terminal), and if not, writing i to the terminal. The $X variable - and hence, this sort of deep inseparability from the terminal - is a first-class feature of MUMPS. Yikes.

\$\endgroup\$
17
\$\begingroup\$

PowerShell, 78 68 61 54 51 Bytes

(-1 byte thanks to a person on Twitter that explicitly started following me just to tag me in a Tweet with a golf, because they don't use SE. I was able to improve on that with a bit more of a golf. But since it requires the new ternary operator in pwsh 7, I'm leaving the old versions present lower down.)

1..100|%{($x="Fizz"*!($_%3)+"Buzz"*!($_%5))?$x :$_}

Loops from 1 to 100, each time constructing $x by exploiting implicit Boolean conversion. That is, if $_%3 is 0, it gets converted to $true with the !, then the * re-converts it to a 1 so that we add on "Fizz" to $x. We encapsulate that construction in parens, so we can re-use it as the introductory query to the ternary operator, choosing to either output $x or $_, depending on whether $x is present.

Normally here is where I'd link it to Try It Online, but that's still on pwsh Core 6.2.3, so doesn't have the ternary operator.


Pre-pwsh 7

1..100|%{(($t="Fizz"*!($_%3)+"Buzz"*!($_%5)),$_)[!$t]}

Edit: Saved 10 bytes thanks to feersum

Edit2: Realized that with feersum's trick, I no longer need to formulate $t as a string-of-code-blocks

Edit3: Saved another 7 bytes thanks to Danko Durbić

Similar-ish in spirit to the stock Rosetta Code answer, but golfed down quite a bit.

Explanation

1..100|%{...} Create a collection of 1 through 100, then for-each object in that collection, do

(...,$_) create a new collection of two elements: 0) $t=... set the variable $t equal to a string;

  1. $_ our-current-number of the loop

"Fizz"*!($_%3) take our-current-number, mod it by 3, then NOT the result. Multiply "Fizz" by that, and add it to the string (and similar for 5). PowerShell treats any non-zero number as $TRUE, and thus the NOT of a non-zero number is 0, meaning that only if our-current-number is a multiple of 3 will "Fizz" get added to the string.

[!$t] indexes into the collection we just created, based on the value of the string $t -- non-empty, print it, else print our-current-number


Alternatively, also 54 bytes

1..100|%{'Fizz'*!($_%3)+'Buzz'*!($_%5)-replace'^$',$_}

Thanks to TesselatingHeckler

Similar in concept, this uses the inline -replace operator and a regular expression to swap out an empty string ^$ with our-current-number. If the string is non-empty, it doesn't get swapped.


Alternatively, also 54 bytes

1..100|%{($_,('Fizz'*!($_%3)+'Buzz'*!($_%5))|sort)[1]}

This is the same loop structure as above, but inside it sorts the pair (n, string), and relies on the fact that an empty string sorts before a number, but a FizzBuzz string sorts after a number. Then it indexes the second sort result.

\$\endgroup\$
6
  • \$\begingroup\$ As an aside, if PowerShell ever implemented the || operator, like in C#, we could likely get down to 43 bytes with something similar to 1..100|%{"Fizz"*!($_%3)+"Buzz"*!($_%5)||$_} ... doubtful, since the | is such an important special operator in PowerShell, but I can dream ... \$\endgroup\$ Commented Sep 24, 2015 at 20:51
  • 1
    \$\begingroup\$ How about 1..100|%{'Fizz'*!($_%3)+'Buzz'*!($_%5)-replace'^$',$_} for 54? \$\endgroup\$ Commented Sep 25, 2015 at 6:18
  • \$\begingroup\$ You can replace if($t){$t}else{$_} with something like ($t,$_)[!$t] \$\endgroup\$ Commented Sep 25, 2015 at 7:03
  • 1
    \$\begingroup\$ ... so you get 1..100|%{(($t="Fizz"*!($_%3)+"Buzz"*!($_%5)),$_)[!$t]} which is also 54 like @TessellatingHeckler's suggestion \$\endgroup\$ Commented Sep 25, 2015 at 8:01
  • \$\begingroup\$ @TessellatingHeckler PowerShell is nothing if not flexible. \$\endgroup\$ Commented Sep 26, 2015 at 0:34
16
\$\begingroup\$

Clojure, 113 106 101 100 91 bytes

My first golf!

(dotimes[i 100](println(str({2'Fizz}(mod i 3))({4'Buzz}(mod i 5)({2""}(mod i 3)(inc i))))))

Ungolfed:

(dotimes [i 100] ; account for off-by-one later
  (println (str ({2 'Fizz} ; str converts symbols to strings
                 (mod i 3))
                ({4 'Buzz} ; 4 instead of 0 because of off-by-one
                 (mod i 5)
                 ({2 ""} ; shortest way to write when-not
                  (mod i 3)
                  (inc i))))))
\$\endgroup\$
3
  • 1
    \$\begingroup\$ You can remove 5 characters by handling the println the same way as in the Java solution, eg. (doall(map #(let[t(=(mod % 3)0)](println(str(if t"Fizz""")(if(=(mod % 5)0)"Buzz"(if t""%)))))(range 1 101))) \$\endgroup\$
    – resueman
    Commented Sep 25, 2015 at 14:47
  • 1
    \$\begingroup\$ @resueman Thanks! It actually ended up being 7, because (if t"Fizz""") can be simplified to (if t"Fizz"). :) \$\endgroup\$
    – Sam Estep
    Commented Sep 25, 2015 at 16:49
  • \$\begingroup\$ +1 Nice modulo trick, at first I though you had off-by-one errors. \$\endgroup\$
    – coredump
    Commented Sep 28, 2015 at 8:09
14
\$\begingroup\$

Hexagony, 112 bytes

d{$>){*./;\.}<._.zi...><{}.;/;$@-/=.*F;>8M'<$<..'_}....>.3'%<}'>}))'%<..._>_.'<$.....};u..}....{B.;..;.!<'..>z;/

After unfolding and with colour-coded execution paths:

enter image description here
Diagram created with Timwi's HexagonyColorer.

Finally got around to finishing this. I had written an ungolfed solution weeks ago, but wasn't entirely happy with it so I never actually golfed it. After revisiting it the other day, I found a way to simplify the ungolfed solution slightly, and while I think there might still be a better way to approach the problem in general, I decided to golf it this time. The current solution is far from optimal, and I think it should actually fit in side-length 6 instead of 7. I'll give this a go over the next days, and when I'm happy with the result will add a full explanation.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ That execution is a mess :P \$\endgroup\$ Commented Nov 8, 2015 at 21:12
  • \$\begingroup\$ @LegionMammal978 I've seen worse. ;) \$\endgroup\$ Commented Nov 8, 2015 at 21:13
  • \$\begingroup\$ How do you create those diagrams? \$\endgroup\$ Commented Nov 8, 2015 at 21:18
  • \$\begingroup\$ @LegionMammal978 Oh, I forgot to add the usual credits: github.com/Timwi/HexagonyColorer \$\endgroup\$ Commented Nov 8, 2015 at 21:18
14
\$\begingroup\$

brainfuck, 411 350 277 258 bytes

Edits:

  • -61 bytes by storing the values of "Fizz Buzz" as "BuziF" "BuziG" and redoing the number printing section.

  • -71 bytes by redoing the modulo number printing section, splitting the loop counter and the number counter, and reusing the newline cell as the mod value, among other things

  • -19 bytes by realising that there aren't any 0s in any FizzBuzz numbers. Also added explanation

+[-[>+<<]>-]>--[>+>++>++>++++++>+>>>++++++[<<<]>-]<+++++[>+>+>->>->++>>>-->>>++[<<<]>>>-]>[>]+++>>[>+<<<-[<]<[>+++>+<<-.+<.<..[<]<]>>-[<<]>[.>.>..>>>>+[<]+++++<]>[>]>>[[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]>,>[>]<[>-[<+>-----]<---.,<]++++++++++>]<.<<<<,>-]

Try it online!

Instead of checking if the number itself was divisible by 5 or 3 I had two counters keeping track of the modulo of the number, decrementing them for each number and printing out the corresponding word when they reached 0.

How It Works:

+[-[>+<<]>-]>--  Generate the number 61
[>+>++>++>++++++>+>>>++++++[<<<]>-] Set the tape to multiples of 61
TAPE: 0 0' 61  122 122 110 61  0 0 110
           "=" "z" "z" "n" "="
<+++++[>+>+>->>->++>>>-->>>++[<<<]>>>-]>[>]+++>> Modify values by multiples of 5
TAPE: 0' 5 66  117 122 105 71  3 0 100' 0 0 10
           "B" "u" "z" "i" "G"
Some info:
  5     - Buzz counter
  "Buz" - Buzz printing
  "ziG" - Fizz printing. Modifying the G in the loop is shorter than modifying it outside
  3     - Fizz counter
  0     - This is where the Fizz|Buzz check will be located
  100   - Loop counter
  0     - Number counter. It's not worth it to reuse the loop counter as this.
  0     - Sometimes a zero is just a zero
  10    - Value as a newline and to mod the number by
  
[ Loop 100 times
  >+<<<  Increment number counter
  -[<]<  Decrement Fizz counter
  [ If Fizz counter is 0
    >+++ Reset the Fizz counter to 3
    >+<< Set the Fizz|Buzz check to true
    -.+<.<.. Print "Fizz"
  [<]<] Sync pointers
  >>-[<<]> Decrement Buzz counter
  [ If Buzz counter is 0
    .>.>.. Print "Buzz"
    >>>>+  Set the Fizz|Buzz check to true
    [<]+++++< Reset the Buzz counter to 5
  ]
  >[>]>> Go to Fizz|Buzz check
  [ If there was no Fizz or Buzz for this number
    TAPE: 3% BuziG 5% 0 Loop Num' 0 10
    [->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]  Mod the number counter by 10
    TAPE: 3% BuziG 5% 0 Loop 0' Num 10-Num%10 Num%10 Num/10
    >[-<+>] Move Num back in place
    >,>[>]< Reset 10-Num%10
    [ For both Num/10 (if it exists) and Num%10
      >-[<+>-----]<--- Add 48 to the number to turn it into the ASCII equivilent
      .,< Print and remove
    ]
    ++++++++++> Add the 10 back
  ]
  <. Print the newline
  <<<<, Remove Fizz|Buzz check
  >- Decrement Loop counter
]
\$\endgroup\$
1
  • \$\begingroup\$ Well done Jo! I might try to beat that someday :) \$\endgroup\$ Commented Dec 15, 2017 at 16:33
1
2 3 4 5
15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.