152
\$\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.

  • Unlike our usual rules, 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\$
  • 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 Sep 24 '15 at 20:47
  • \$\begingroup\$ @AShelly Only when running \$\endgroup\$ – Beta Decay Sep 24 '15 at 20:48
  • \$\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 Sep 24 '15 at 23:28
  • 8
    \$\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 Sep 25 '15 at 0:50
  • 61
    \$\begingroup\$ A "vanilla fizzbuzz" sounds delicious. \$\endgroup\$ – Reinstate Monica -- notmaynard Sep 25 '15 at 15:12

278 Answers 278

1 6 7 8 9 10
1
\$\begingroup\$

TIS, 573 + 48 = 621 bytes

Code (573 bytes):

@0
MOV ANY DOWN
MOV ANY RIGHT
@1
MOV ANY DOWN
ADD DOWN
MOV ANY DOWN
ADD DOWN
MOV ANY LEFT
MOV LEFT DOWN
ADD DOWN
@2
SUB 101
JLZ C
HCF
C:ADD 102
MOV ACC LEFT
@3
MOV ANY DOWN
MOV ANY UP
@4
MOV UP DOWN
MOV ANY UP
MOV UP DOWN
MOV ANY UP
MOV UP DOWN
MOV ANY UP
MOV UP DOWN
MOV ANY UP
MOV UP RIGHT
MOV ANY DOWN
MOV ANY UP
@5
MOV ANY DOWN
MOV ANY LEFT
@6
ADD UP
MOV 70 DOWN
MOV 105 DOWN
MOV 122 DOWN
MOV 122 DOWN
MOV 0 UP
@7
MOV UP ACC
JEZ N
MOV ACC DOWN
N:MOV -1 RIGHT
MOV 0 UP
@8
MOV ANY ACC
JLZ N
MOV 66 DOWN
MOV 117 DOWN
MOV 122 DOWN
MOV 122 DOWN
MOV 0 UP
JRO -7
N:MOV 10 DOWN

Layout (48 bytes):

3 3
CCCCCCCCC
O0 ASCII -
O1 NUMERIC -
O2 ASCII -

Try it online!

Explanation

I think my TIS emulator is ready for its debut! This is an emulator inspired by (and based on) the wonderful game TIS-100. However, where the game only emulates the 100 model of the TIS series, I have designed this emulator to reflect the full range of possibilities.

The code is in the format standardized by the game; we'll get to that in a bit. But first, the layout description just below that.

Layout

This is a specification for which model and configuration within the TIS range we desire. Whereas the model in the game (also called TIS-100) is only found in a 3 rows by 4 columns layout, for this solution I require something different.

I desire a 3 by 3 square instead. Since there are multiple types of nodes that can fall in each slot, I specify that all nine are Compute nodes (other types include e.g. stack memory).

In a TIS, the top row of nodes may read in input from above themselves (if so configured) and the bottom row may write below themselves to perform output (again, if so configured). For this challenge, no Inputs are needed, but I desire three different Outputs, corresponding to the three columns in this layout.

The first and third column outputs (O0 and O2) are each in ASCII mode; this means that they will translate the internal numeric type to an ASCII character when performing output. The center column (O1) is a NUMERIC output, meaning that the values sent to this output will instead be written out as a number. In all cases, we want the data to go to stdout (-).

Putting all this together gives the layout file seen above.

Code

TIS assembly code is stored in a flat file, as seen above. The code under the heading @0 will go in the first compute node, @1 in the second compute node, and so on. The layout in this solution looks like this:

0 1 2
3 4 5
6 7 8

Since each compute node only has capacity for 15 lines of code, my solution distributes the primary logic across 6 different nodes (the other three just bus data back and forth). Those 6 nodes are as follows:

Node @2, the top right, is the counter, counting 1 through 100, and terminating execution (HCF) upon reaching 101.

Node @1, the top center, sends every third number left (for Fizz), and all numbers down.

Node @6, the bottom left, produces "Fuzz" when given any number.

Node @4, the true center, sends every fifth number right (for Buzz), and all numbers down.

Node @8, the bottom right, produces "Buzz" when given a non-negative number and "\n" otherwise.

Node @7, the bottom center, produces a number if that number hasn't already been Fizzed or Buzzed (or both), and then requests a newline to be printed.

It is quite possible that this is not yet a fully optimal golf, but this is also the first golf I've done for TIS.

\$\endgroup\$
  • \$\begingroup\$ Hmm, I'm thinking that due to the decisions here, especially point 2, I could argue for not including the layout in the byte count. It is a 'different implementation', essentially. Opinions appreciated. \$\endgroup\$ – Phlarx Mar 29 '18 at 21:31
1
\$\begingroup\$

Jstx, 36 bytes

₧&0←+☺:@♥>ø↕₧K2→+◙♣>ø↕₧O2→+◙%↓2◙∟416

Explanation

₧& # Push literal 100
0  # Enter an iteration block over the first stack value and push the iteration element register at the beginning of each loop.
←  # Push literal false
+  # Store the first stack value in the a register.
☺  # Push literal 1
:  # Push the sum of the second and first stack values.
@  # Push three copies of the first stack value.
♥  # Push literal 3
>  # Push the modulus of the second and first stack values.
ø  # Push literal 0
↕  # Enter a conditional block if the top two stack values are equal.
₧K # Push literal Fizz
2  # Print the first stack value.
→  # Push literal true
+  # Store the first stack value in the a register.
◙  # End a conditional block.
♣  # Push literal 5
>  # Push the modulus of the second and first stack values.
ø  # Push literal 0
↕  # Enter a conditional block if the top two stack values are equal.
₧O # Push literal Buzz
2  # Print the first stack value.
→  # Push literal true
+  # Store the first stack value in the a register.
◙  # End a conditional block.
%  # Push the value contained in the a register.
↓  # Enter a conditional block if first stack value exactly equals false.
2  # Print the first stack value.
◙  # End a conditional block.
∟  # Push literal null
4  # Print the first stack value, then a newline.
1  # End an iteration block.
6  # Ends program execution.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Phooey, 57 bytes

&1[101>&0<@@%3{"Fizz">&1<}&%5{"Buzz">&1<}&>{<$i>}$c10<+1]

Try it online!

Explanation

&1                    set current cell to 1
[101                  until that cell is 101:
  >&0<                zero the cell to the right
  @@                  push two copies of the current cell to the stack
  %3{"Fizz">&1<}      if it's divisible by 3, print "Fizz"
  &%5{"Buzz">&1<}     if it's divisible by 5, print "Buzz"
  &                   restore cell
  >{<$i>}             if it's not, print the restored cell
  $c10                print a newline
  <+1                 increment the current cell
]
\$\endgroup\$
  • \$\begingroup\$ This actually doesn't look like such a bad language \$\endgroup\$ – ASCII-only Apr 20 '18 at 13:02
  • \$\begingroup\$ @ASCII-only Thank you! \$\endgroup\$ – Conor O'Brien Apr 20 '18 at 13:05
  • \$\begingroup\$ There's only one problem: this is nothing like Foo :P \$\endgroup\$ – ASCII-only Apr 20 '18 at 13:16
  • \$\begingroup\$ @ASCII-only This is strikingly like foo, actually. The only thing in this answer unlike foo are the new while loops [...] \$\endgroup\$ – Conor O'Brien Apr 20 '18 at 13:18
  • \$\begingroup\$ >_> actually... have I spent my entire life thinking the meme language Foo/how it's represented in the meme post was actually all Foo did \$\endgroup\$ – ASCII-only Apr 20 '18 at 13:33
1
\$\begingroup\$

ORACLE SQL (107 bytes)

select nvl(decode(mod(rownum,3),0,'Fizz')||decode(mod(rownum,5),0,'Buzz'),rownum)from xmltable('1 to 100')

DEMO

\$\endgroup\$
1
\$\begingroup\$

Pyret, 150 bytes

d={(a,b):if num-modulo(a,b) == 0:if b == 3:"Fizz"else:"Buzz" end else:""end}
each({(y):q=d(y,3) + d(y,5)
print(if q == "":y else:q end)},range(1,101))

You can try this online by copying it into the online Pyret editor!

Pyret is a language designed with education in mind, so there's a couple things it enforces to keep things readable in normal programs. This explains why some of the operators are surrounded by spaces and the presence of newlines in the program.

The {(...): ...} syntax is shorthand for lambda expressions, which gives us the following ungolfed version:

d = lam(a,b):
  if num-modulo(a,b) == 0:
    if b == 3:
      "Fizz"
    else:
      "Buzz" 
    end 
  else:
    ""
  end
end

each(
  lam(y):
    q = d(y,3) + d(y,5)
    print(
      if q == "":
        y 
      else:
        q 
      end)
  end,
  range(1,101))
\$\endgroup\$
1
\$\begingroup\$

Python 2.7, 105 bytes

for i in range(1,101):
 w=''
 if i%3==0:w+='Fizz'
 if i%5==0:w+='Buzz'
 if w!='':print w
 else:print i

I know this can be golfed a lot. But I don't know how though.

\$\endgroup\$
  • 1
    \$\begingroup\$ General golf tip that is surprisingly pythonic: w!='' can be w. \$\endgroup\$ – Jonathan Frech Jul 18 '18 at 11:07
  • \$\begingroup\$ Though for a more golfed version of the straight-forward approach, see this answer. \$\endgroup\$ – Jonathan Frech Jul 18 '18 at 11:12
1
\$\begingroup\$

Lua, 80 bytes

Can probably be improved:

s=("").sub for i=1,100 do r=s("Fizz",i%3*5)..s("Buzz",i%5*5)print(r..s(i,#r))end

Readable version:

s=("").sub
for i=1,100 do
  r=s("Fizz",i%3*5)..s("Buzz",i%5*5)
  print(r..s(i,#r))
end
\$\endgroup\$
1
\$\begingroup\$

Groovy, 63 bytes

Stand-alone program, prints result to STDOUT.

100.times{n->s=(++n%3?'':'Fizz')+(n%5?'':'Buzz')
println s?s:n}

I'd have preferred to use (1..100).each{ instead of 100.times{, so that I didn't have to ++n at the start of each iteration, but this is golf and that saves me two bytes.

Other than that, a pretty standard truthy-based submission. 'Fizz' and 'Buzz' are added when remainder is 0 because 0 is falsy, and '' is a falsy string, so I can print n when the first line hasn't had either of 'Fizz' or 'Buzz' added.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Python 3, 62 bytes

for _ in range(1,101):print("Fizz"*(_%3<1)+"Buzz"*(_%5<1)or _)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

K (oK), 49 46 43 bytes

Solution:

`0:{$[a:,/$&`Fizz`Buzz!~5 3!'x;a;x]}'1+!100

Try it online!

Explanation:

`0:{$[a:,/$&`Fizz`Buzz!~5 3!'x;a;x]}'1+!100 / the solution
                                       !100 / range 0..99
                                     1+     / add 1
   {                               }'       / apply lambda {} to each number
    $[                        ; ; ]         / conditional, $[if;then;else] 
                        5 3!'x              / apply modulo (!) of each 5 and 3 to the input x
                       ~                    / not (0->1, anything else->0)
            `Fizz`Buzz!                     / turn results into a dictionary
           &                                / keys where true
          $                                 / convert to strings
        ,/                                  / flatten
      a:                                    / save as a
                               a            / result if a is not empty - so Fizz / Buzz
                                 x          / result if a is empty - so 1, 2, 4
`0:                                         / print to stdout

Notes:

  • -6 bytes thanks to @ngn with a new approach
\$\endgroup\$
  • 1
    \$\begingroup\$ 2 2/ -> 2/­­­­, @' -> ' \$\endgroup\$ – ngn Oct 1 '18 at 3:48
  • \$\begingroup\$ it produces the same output without the $ \$\endgroup\$ – ngn Oct 2 '18 at 13:13
  • \$\begingroup\$ `Fizz`Buzz`FizzBuzz -> a,,,/$a:`Fizz`Buzz \$\endgroup\$ – ngn Oct 2 '18 at 13:18
  • 1
    \$\begingroup\$ and here's a slightly shorter one abusing "where" on dicts: `0:{$[a:,/$&`Fizz`Buzz!~5 3!'x;a;x]}'1+!100 \$\endgroup\$ – ngn Oct 2 '18 at 13:37
1
\$\begingroup\$

APL(NARS), 44, 43, 39 chars 78 bytes

⊃{⍱/z←0=3 5∣⍵:⍕⍵⋄∊z/'fizz' 'buzz'}¨⍳100

In practice I follow Adam suggest.

I had seen other APL solutions, so I copied the way. In the follow APL code, ←A here suppress the output of A.

←{⎕←∊{∨/j←0=3 5∣⍵:j/'fizz' 'buzz'⋄⍵}⍵}¨⍳100

{⎕←∊{∨/j←0=3 5∣⍵:j/'fizz' 'buzz'⋄⍵}⍵⋄⍬}¨⍳100 This above should return at end 100 void list, but it seems they are not showed at last here.

{⎕←{×+/j←0=3 5∣⍵:⊃,/j/'fiz' 'buz'⋄⍵}⍵⋄⍬}¨⍳100 This just above has one error because fiz and buz should be fizz and buzz

{⎕←{0<+/j←0=(3 5)∣⍵:⊃,/j/('fiz' 'buz')⋄⍵}⍵⋄⍬}¨⍳100

:for i:in⍳100⋄{0<+/j←0=(3 5)∣⍵:⊃,/j/('fiz' 'buz')⋄⍵}i⋄:endfor

\$\endgroup\$
  • \$\begingroup\$ Ever so slightly golfed (and adding the missing "z"s): ⊃{∨/j←0=3 5∣⍵:∊j/'fizz' 'buzz'⋄⍕⍵}¨⍳100 \$\endgroup\$ – Adám Dec 7 '17 at 23:45
1
\$\begingroup\$

Alchemist, 101 bytes

0x+f+b->Out__+x+b
0x+0f->Out_"Fizz"+2f+x
0x+0b+f->Out_"Buzz"+5b+x
x+0b->f
x+b+a->_+Out_"\n"!99a+2f+4b

Try it online!

Takes a few confusing shortcuts in order to reuse the Buzz for FizzBuzzs.

Explanation:

!99a+2f+4b           # Initialise the program with 
                         # 99a (overall counter)
                         # 2f (Fizz counter)
                         # 4b (Buzz counter)
                         # 1_ (num counter)

0x+f+b->Out__+x+b        # If there's a Fizz and Buzz counter, print the current number
                         # Also decrement the Fizz counter
0x+0f->Out_"Fizz"+2f+x   # If there's no Fizz counter, print Fizz
                         # And reset the Fizz counter
0x+0b+f->Out_"Buzz"+5b+x # If there's no Buzz counter and there is a Fizz counter, print Buzz
                         # Reset the Buzz counter
                         # And decrement the Fizz counter

# After we've printed any of these, set the x flag
x+0b->f                  # If there is also no Buzz counter, go back to the Buzz printer
                         # This is to ensure the Buzz check comes after the Fizz check
x+b+a->_+Out_"\n"        # Otherwise, decrement the total counter
                         # Decrement the Buzz counter
                         # Increment the num counter
                         # And print a newline
\$\endgroup\$
1
\$\begingroup\$

JavaScript, 73 71 65 bytes

for(i=1;i<101;i++)console.log((i%3?"":"Fizz")+(i%5?"":"Buzz")||i)
\$\endgroup\$
  • \$\begingroup\$ This was my first answer, what was the problem with the format? \$\endgroup\$ – Diego Torres Sep 25 '15 at 13:57
  • \$\begingroup\$ Generally, language and size headers should be a header. Also, your current code doesn't seem to work, but you can fix it by replacing console.info with writeln (I tested it here and it worked.) \$\endgroup\$ – ASCIIThenANSI Sep 25 '15 at 13:59
  • \$\begingroup\$ Do I need to specify the size or only the language? writeln is not valid in JavaScript, console.info is like console.log; both are valid. \$\endgroup\$ – Diego Torres Sep 25 '15 at 14:08
  • \$\begingroup\$ Ah, OK, didn't realize that about writeln. You have to specify both the language and the size, on the same line. Also, I would reccommend using console.log if possible, that'll save you an extra byte. \$\endgroup\$ – ASCIIThenANSI Sep 25 '15 at 14:13
  • \$\begingroup\$ Also, welcome to PPCG! \$\endgroup\$ – AdmBorkBork Sep 25 '15 at 14:13
1
\$\begingroup\$

Brachylog, 48 bytes

100⟦₁{f{∋15∧"FizzBuzz"|∋3∧"Fizz"|∋5∧"Buzz"|t}ẉ}ᵐ

Try it online!

Probably not golfed too well but it works.

\$\endgroup\$
1
\$\begingroup\$

C++ 123 122 bytes -1 thanks to JonathanFrech

#import<iostream>
#define s std::cout<<
main(){for(int i;100-i++;s(i%3?"":"Fizz")<<(i%5?"":"Buzz")<<'\n')i%3*i%5?s i:s"";}
\$\endgroup\$
  • \$\begingroup\$ You can move the declaration of i inside the loop. Furthermore, is this variables initial value guaranteed to be zero? \$\endgroup\$ – Jonathan Frech Mar 22 '19 at 14:36
  • \$\begingroup\$ @JonathanFrech I read somewhere that global ints are automatically initialized to 0 \$\endgroup\$ – Yoris Mar 22 '19 at 20:53
1
\$\begingroup\$

C, 98 94 bytes

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

Pretty simple stuff...

Thanks to Yoris Fresh for helping me save a couple bytes. Thanks to Jerry Jeremiah for pointing out a mistake in the ungolfed version.

Ungolfed:

i;
main() {
    for (; ++i < 101;)
        i % 3 && i % 5 ?
            printf("%d\n",i) :
            printf("%s%s\n", i % 3 ? "" : "Fizz", i % 5 ? "" : "Buzz");
}
\$\endgroup\$
  • \$\begingroup\$ the ungolfed version increments i twice each loop. \$\endgroup\$ – Jerry Jeremiah Jun 4 '19 at 3:33
1
\$\begingroup\$

05AB1E, 24 bytes

тÝ3Å€"Fizz"}5Å€á”ÒÖ”J}¦»

Try it online!

Explanation:

тÝ                  # range 0..100
  3Å€      }        # for every 3rd element...
     "Fizz"         # replace it with Fizz    
  5Å€      }        # for every 5th element...
     á              # keep only letters...
      ”ÒÖ”J         # and append "Buzz"
            ¦       # drop the first element
             »      # join with newlines
                    # implicit output

Or alternatively:

тÝ35vyÅ€á”FizzÒÖ”#NèJ]¦»

Try it online!

35vy iterates over the digits of 35, which avoids repeating Å€}. ”FizzÒÖ” is the string Fizz Buzz, and then #Nè selects the appropriate element.

Legacy 05AB1E doesn’t have Å€, so neither of those work for it. However, legacy à (set intersection) implicitly splits numbers, which lets us get a 26 that only works on legacy:

тLεDÑ35Ãvá”Fizz ÒÖ”#yèJ},

Try it online!

тLε                         # for y in 1..100
   DÑ                       # divisors of y
     35Ã                    # keep only those in [3, 5]
        v               }   # for each...
         á                  # keep only letters
          ”Fizz ÒÖ”#yèJ     # append either Fizz or Buzz
                         ,  # print with newline
\$\endgroup\$
1
\$\begingroup\$

Julia, 87 Bytes

for i in 1:100;println(i%3<1 ? "Fizz"*(i%5<1 ? "Buzz" : "") : (i%5<1 ? "Buzz" : i));end

More readable:

for i in 1:100
    if i%3 < 1
        print("Fizz")
        if i%5 < 1
            println("Buzz")
        else
            println()
        end
    elseif i%5 < 1
        println("Buzz")
    else
        println(i)
    end
end

Not sure if there's already a Julia submission here. Also my first time golfing c:

Indirect thanks to @Najkin because I saw their reply to a C# submission saying that you can use <1 instead of ==0 and that helped me save 3 bytes over my previous 90-byte solution!

BTW if you see any "unnecessary" spaces, they're actually necessary as Julia would throw a syntax error without them. (Why?!)

\$\endgroup\$
  • \$\begingroup\$ oh I just realized there's a 72-byte Julia submission lol \$\endgroup\$ – Sagittarius Aug 28 '19 at 14:02
1
\$\begingroup\$

Hoon, 115 bytes

This is a Hoon say generator which can be used to write the output to a file from the dojo.

turn is Hoon's map, it takes a list from 1..100 generated via (gulf 1 100) and uses string interpolation and the 'null check' conditional rune ?~ to generate either "Fizz", "Buzz" or "FizzBuzz" according to the value of x. This is paired with the value of x as a string <x> and then - and + are used to select the fizzbuzz string if not empty, otherwise the number string from the pair.

:-
%say
|=
*
:-
%txt
%+
turn
(gulf 1 100)
|=
x=@
=>
"{?~((mod x 3) "Fizz" ~)}{?~((mod x 5) "Buzz" ~)}"^<x>
?~
-
+
-
\$\endgroup\$
1
\$\begingroup\$

Ink, 77 70 57 48 bytes

-(n){n%3:{n%5:{n}}|Fizz}{n%5: |Buzz}
{n<100:->n}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Wren, 78 bytes

It turns out that this is pretty hard to golf.

for(i in 1..100)System.print(i%15==0?"FizzBuzz":i%5==0?"Buzz":i%3==0?"Fizz":i)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Keg, 58 44 bytes

`Fizz``Buzz`1(d|:3%[|0⊙,]:5%[:3%[:.]|1⊙,]
,⑨

Try it online!

-14 bytes thanks to @EdgyNerd

Answer History

58 bytes

1(d|:\“%0=[`FizzBuzz`|:5%0=[`Buzz`|:3%0=[`Fizz`|:⅍]]],
,⑨)

Try it online!

String compression and string formatting are both useless here. Just a standard implementation of Fizzbuzz in Keg.

\$\endgroup\$
  • 1
    \$\begingroup\$ Idea to golf some bytes: couldn't you push an empty string, and then concatenate 'Fizz' if it's a multiple of 3, and then concat 'Buzz' if it's a multiple of 5, to save the FizzBuzz in your code (and probably some other bytes) \$\endgroup\$ – EdgyNerd Dec 1 '19 at 11:08
1
\$\begingroup\$

DIVSPL, 22 bytes

1..100
fizz=3
buzz=5
\$\endgroup\$
1
\$\begingroup\$

Rust, 114 bytes

It's not the shortest one available (on code-golf.io someone managed to somehow solve it in 99 bytes, but I have no idea how).

fn main(){(1..101).for_each(|i|println!("{}",["FizzBuzz","Fizz","Buzz",&i.to_string()][1.min(i%5)+2.min(i%3*2)]))}

First off, the obvious part

fn main() {/*..*/}

Then we iterate from 1 to 100 (inclusive) and println! an element of the array

(1..101).for_each(|i| println!("{}", ["FizzBuzz", "Fizz", "Buzz", &i.to_string()][/*..*/]))

To choose the right index, we use the following, where i is the current number

1.min(i % 5) + 2.min((i % 3) * 2)

The first part is 0 if i is a multiple of 5. Otherwise it's 1.

The second part is 0 if i is a multiple of 3. Otherwise it's 2.

Examples:

1.min(1 % 5) + 2.min((1 % 3) * 2) == 1 + 2 == 3 => "1"
1.min(3 % 5) + 2.min((3 % 3) * 2) == 1 + 0 == 1 => "Fizz"
1.min(4 % 5) + 2.min((4 % 3) * 2) == 1 + 2 == 3 => "4"
1.min(5 % 5) + 2.min((5 % 3) * 2) == 0 + 2 == 2 => "Buzz"
1.min(15 % 5) + 2.min((15 % 3) * 2) == 0 + 0 == 0 => "FizzBuzz"

This way, if both parts produce 0, we get the string FizzBuzz. If the sum is 1 we get Fizz, if it's 2 Buzz, if it's 3 we get &i.to_string() (the stringified number).

\$\endgroup\$
1
\$\begingroup\$

W d, 29 23 bytes

&ó╞╟↨5O╓46N☻»½_49ƒZÄ▬«Σ

A raw source is here.

After decompression:

2^                         E % Foreach in the 1..100 range
        a3m!                 % If the current item is divisible by 3:
  "Fizz"    *                % Return "Fizz"
             "Buzz"a5m!*     % If the current item | 3 -> "Buzz".
                        +    % Join those results
                         a|  % Logical OR this result with the current item
                              % Implicit print
\$\endgroup\$
0
\$\begingroup\$

Python

[[x,"fizz","buzz","fizzbuzz"][(x%3<1 and 1)+(x%5<1 and 2) or 0] for x in range(100)]
\$\endgroup\$
  • 7
    \$\begingroup\$ Welcome to PPCG! I'm afraid this doesn't quite satisfy the spec of the challenge. This appears to be a (REPL?) snippet (not a full program), which evaluates to a list (instead of printing the results to STDOUT line by line) and doesn't use the right capitalisation (capital F and B) and also seems to have the range from 0 to 99 instead of 1 to 100. \$\endgroup\$ – Martin Ender Sep 27 '15 at 20:28
  • \$\begingroup\$ Override header: Invalid - See what Martin said above ^ \$\endgroup\$ – Beta Decay Nov 1 '15 at 8:53
  • \$\begingroup\$ You can use int(i%5<1) to save some bytes \$\endgroup\$ – maxb Sep 14 '18 at 17:00
0
\$\begingroup\$

Scala, 103 94 bytes

for{i<-1 to 100;s=(if(i%3==0)"Fizz"else"")+(if(i%5==0)"Buzz"else"")}println(if(s=="")i else s)

thx @Ben (shortened by 9 bytes)

\$\endgroup\$
  • \$\begingroup\$ You can save 9 bytes by using a for comprehension: for{i<-1 to 100;s=(if(i%3==0)"Fizz"else"")+(if(i%5==0)"Buzz"else"")}println(if(s=="")i else s) \$\endgroup\$ – Ben Oct 2 '15 at 20:57
0
\$\begingroup\$

Javascript ES6, 77 chars

"\n".repeat(100).replace(/(?=\n)/g,(m,i)=>(++i%3?m:"Fizz")+(i%5?m:"Buzz")||i)

Test:

"\n".repeat(100).replace(/(?=\n)/g,(m,i)=>(++i%3?m:"Fizz")+(i%5?m:"Buzz")||i) == document.querySelector("pre").textContent
\$\endgroup\$
  • \$\begingroup\$ Here's my ES6 attempt, with parts stolen from yours (89 chars): "0".repeat(99).split(0).map((m,i)=>{return(++i%3?m:"Fizz")+(i%5?m:"Buzz")||i}).join("\n") \$\endgroup\$ – starbeamrainbowlabs Jan 7 '16 at 6:48
  • \$\begingroup\$ @starbeamrainbowlabs, why do you use {return ...} instead of expression? \$\endgroup\$ – Qwertiy Jan 7 '16 at 10:21
  • \$\begingroup\$ Because I couldn't get the expression to work :( \$\endgroup\$ – starbeamrainbowlabs Jan 7 '16 at 16:20
  • \$\begingroup\$ Save a byte by using template strings + literal newline at front. \$\endgroup\$ – Mama Fun Roll Jan 29 '16 at 0:34
0
\$\begingroup\$

Python 91 Bytes

for n in range(100):
    c=""
    if n%3==0:c+="fizz"
    if n%5==0:c+="buzz"
    if c=="":c=n
    print c
\$\endgroup\$
0
\$\begingroup\$

Elixir, 182 bytes

import Stream
f=fn(n)->(zip(cycle(["","","fizz"]),cycle(["","","","","buzz"]))|>zip(iterate(1,&(&1 + 1)))|>map(fn{{"",""},n}->n
{{p,o},_}->p<>o end))|>take(n)|>Enum.each(&IO.puts/1)end

LiveDemo

Calling: f.(100)

\$\endgroup\$
1 6 7 8 9 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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