155
\$\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>

| improve this question | | | | |
\$\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

279 Answers 279

1 2 3
4
5
10
3
\$\begingroup\$

Minkolang, 50 bytes

"d"[i1+d5%6&"Buzz"0c3%6&"Fizz"I1-3&N6@0gx(O)25*O].

Try it here.

Explanation

"d"[...].        For loop that loops from 0 to 99, then stops
i1+              Loop counter + 1 (so it's 1 to 100)
d5%6&"Buzz"      Divisibility test by 5, skips "Buzz" if not divisible
0c3%6&"Fizz"     Divisibility test by 3, skips "Fizz" if not divisible
I1-              Length of stack minus 1 (0 if there's no Fizz or Buzz)
3&N6@            Output as integer if ^ is 0, skip character output otherwise
0gx(O)           Dump the loop counter and output "Fizz"/"Buzz"/"FizzBuzz"
25*O             Print newline
| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Jolf, 42 33 31 bytes

Try it here! Replace ƒ with \x9f. I'm stealing ETHproduction's method of fizzbuzzing.

ƒΜz~1d|]"FizzBuzz"?%H340?%H548H

Old version, 42 bytes

γ"Fizz"ƒΜz~1d?mτͺ35H+γζ?m|3Hγ?m|5HΖ"Buzz"H
γ"Fizz"                                     γ = "Fizz"
        Μz~1d                               map 1..100 with the following function
             ?mτͺ35H                        if both 3 and 5 | H
                    +γζ                      return γ + ζ
                       m|3H                 else if 3 | H
                           γ                 return γ
                             ?m|5H          else if 5 | H
                                  Ζ"Buzz"    return ζ = "Buzz"
                                         H  else return H
       ƒ                                    join by newlines

I might be able to golf it down by using the dictionary in Jolf, but who would want to with such a perfect score?

| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Python 2 REPL, 54

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

Based on this answer by feersum. Essentially the same technique, only using Python's underscore variable to save 2 chars at the start.

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ You should probably specify this answer as "Python 2 REPL", as opposed to feersum's which is a full program. \$\endgroup\$ – Sp3000 Mar 7 '16 at 2:26
  • \$\begingroup\$ @Sp3000 Done and done. \$\endgroup\$ – Tersosauros Mar 7 '16 at 2:37
3
\$\begingroup\$

Vim, 66, 57 56 keystrokes

i1<esc>qqYp<C-a>q98@q3Gqy:s/\d*/Fizz<CR>3j@yq@y5Gqz:s<CR>ABuzz<esc>5j@zq@z

Further golfing, and explanation on the way.

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ A bit too late, but apparently this doesn't output correctly: Try it online! \$\endgroup\$ – user41805 May 16 '17 at 9:47
3
\$\begingroup\$

Ruby, 82 72 70 68 bytes

based on other answers:

puts (1..100).map{|i|(x=(i%3<1?"Fizz":"")+(i%5<1?"Buzz":""))>""?x:i}

old solution:

(1..100).map{|i|$><<"Fizz"if f=i%3<1
$><<"Buzz"if b=i%5<1
$><<i if !(f||b)
puts()}
| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

APL, 41 bytes

⊣{⎕←∊(z,⍱/z←0=3 5|⍵)/'Fizz' 'Buzz'⍵}¨⍳100

Tested on GNU-APL (ver 1.7/980M)

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Do you need the space between ' and ? \$\endgroup\$ – Zacharý Aug 3 '17 at 20:34
  • \$\begingroup\$ Oh, I haven't used GNU APL in a while, is the needed, since you display directly to STDOUT? \$\endgroup\$ – Zacharý Aug 4 '17 at 22:15
  • \$\begingroup\$ @Zacharý In GNU-APL monadic 'left tack' discards the value of the right argument. I read it as return nothing (since it points to left). I hope this is the correct way to phrase it. on the other hand, I do not have experience with Dyalog or a ready-setup to play with. \$\endgroup\$ – Ala'a Mohammad Aug 6 '17 at 18:45
  • \$\begingroup\$ Oh, for some reason I was thinking the return value was not written to STDOUT by default. \$\endgroup\$ – Zacharý Aug 6 '17 at 19:05
3
\$\begingroup\$

TeX, 304 bytes

\documentclass[9pt,a4paper]{article}\pagestyle{empty}\begin{document}\count0=0\count1=0\count3=3\count5=5\loop\advance\count1 by1\count0=0
\ifnum\count1=\count3 Fizz\advance\count3 by3\count0=1\fi\ifnum\count1=\count5 Buzz\advance\count5 by5\count0=1\fi\the\count1

\ifnum\count1<100\repeat\end{document}

Somehow count0 is necessary but I didn't check whether it is zero. It works and I have no idea why.

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ I'm assuming that extra newline is there for a reason, but what's the reason? \$\endgroup\$ – Stephen Aug 20 '17 at 0:06
  • 1
    \$\begingroup\$ @StepHen two newlines is a new paragraph \$\endgroup\$ – Leaky Nun Aug 20 '17 at 0:06
3
\$\begingroup\$

AppleScript, 104 102 100 bytes

""
repeat with i from 1to 100
result&{"FizzBuzz",i,"Fizz","Buzz"}'s item((i^4mod 15+7)div 4)&"
"
end

If you run it in Script Editor, the result has "quotes" around it. If you run it with osascript, there are no "quotes", but the result ends with an extra blank line.

I steal the technique from Lynn's Lua answer, where the script picks from a list of possible values to print. I use (i^4mod 15+7)div 4 to calculate the index 1, 2, 3, or 4. It's different from Lua's i^2%3+i^4%5*2+1.

In AppleScript, i^4 raises i to 4th power. It returns a real, which is a floating-point number, but the value is equal to the correct integer.

The values of n = i^4mod 15 with i from 1 to 15 are

i = 1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
n = 1   1   6   1  10   6   1   1   6  10   1   6   1   1   0

So n is 0.0 for "FizzBuzz", 1.0 for i, 6.0 for "Fizz", or 10.0 for "Buzz". This pattern continues with i from 16 to 100. I need to map the values 0.0, 1.0, 6.0, 10.0 to a list index; lists in AppleScript start at index 1.

n          = 0.0   1.0   6.0  10.0
(n+2)mod 7 = 2.0   3.0   1.0   5.0
(n+7)div 4 = 1     2     3     4

My 104-byte answer used (n+2)mod 7, but that mapping had 5.0 instead of 4.0, so it needed a list of 5 items, where the extra item 0, cost 2 bytes. My 102-byte answer uses (n+7)div 4. My 100-byte answer deletes 2 extra spaces.

| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Excel VBA, 88 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the VBE immediate window.

For i=1To 100:o="":o=IIf(i Mod 3,o,"Fizz"):o=IIf(i Mod 5,o,o+"Buzz"):?IIf(o="",i,o):Next

Ungolfed

For i=1To 100                   ''  iterate from 1 to 100
    o=""                        ''  reset out var at each var
    o=IIf(i Mod 3,o,"Fizz")     ''  set the out var to `Fizz` if i Mod 3 = 0
    o=IIf(i Mod 5,o,o+"Buzz")   ''  append `Buzz` to out var if i Mod 5 = 0
    ?IIf(o="",i,o)              ''  If out var is non-empty, output the out var
                                ''      else output i
Next

Worksheet Version, 97 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the range [C1:C100]

[A1:C100]=Array("=ROW()","=IF(MOD(A1,3),,""FIZZ"")&IF(MOD(A1,5),,""BUZZ"")","=IF(B1="""",A1,B1)")

Ungolfed

[A1:A100]="=ROW()"
[B:B]="=IF(MOD(A1,3),,""FIZZ"")&IF(MOD(A1,5),,""BUZZ"")"
[C:C]="=IF(B1="""",A1,B1)"

Subroutine Version, 110 Bytes

Declared Subroutine that takes no input and outputs to the VBE immediate window

Sub F
For i=1To 100
o=""
If i Mod 3=0Then o="Fizz
If i Mod 5=0Then o=o+"Buzz
Debug.?IIf(o="",i,o)
Next
End Sub
| improve this answer | | | | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You can remove o="": and change your first iif to IIf(i Mod 3,"","Fizz") \$\endgroup\$ – seadoggie01 Sep 7 '18 at 20:53
  • \$\begingroup\$ For the Subroutine version, the () after F isn't optional, and gets added in automatically. Same with the ? in debug. \$\endgroup\$ – Selkie Feb 26 '19 at 18:14
  • 1
    \$\begingroup\$ @Selkie, the behavior you are describing is known as autoformatting, and it is generally accepted in this community for VBA and for all languages that exhibit autoformatting, one may post their code from before it is autoformatted. in this case, that would mean that a couple of spaces may be removed, terminal "s dropped, changing print to ? and removal of the () from the Sub declaration. I suggest that you take a look at the Tips for Golfing in VBA page for more info \$\endgroup\$ – Taylor Scott Feb 26 '19 at 21:30
3
\$\begingroup\$

Hexagony, 77 76 bytes

=?3})"F\>%'5?\"\B;u;"}/4;d'%<>\g/"!{{\}.%<@>'...<>,}/${;;z;i;z;;$/<>?{$/"./_

Try it online!

Same side length as M L's solution, but a bit smaller.

Expanded:

      = ? 3 } ) "
     . \ > % ' 5 ?
    \ F \ B ; u ; "
   } " / ; d ' % < >
  \ g 4 / ! { { \ } . 
 % < @ . > " ' . < > ,
  } / $ { ; ; z ; i ;
   z ; ; $ / < > ? {
    $ / " . / _ . .
     . . . . . . .
      . . . . . .

Coloured 77 byte version (only difference is the bottom right corner):

enter image description here

  • Green: The general outline of the loop
  • Light Blue: "Fizz" printer
  • Dark Blue: "Buzz" printer
  • Yellow: Number printer
  • Red: Terminator path

How it Works:

Memory Model:

enter image description here

  • Num: The counter
  • Mod: The number we are moduloing(?) with the counter
  • Temp: Our calculation edge
  • Check: The FizzBuzz check

Below I'll be referring to the instructions as they are executed, ignoring no-ops and direction changes.

At the start we execute =?3})"%< which increments the counter (initially 0) and checks whether it is divisible by 3. If so, we branch up and execute "F;i;z;;{ which prints "Fizz" in the check edge and returns to the temp edge.

}?5'%>: Now we check if the number is divisible by 5. If so, B;u;"z;; prints "Buzz" in the check edge (the " is out of place to prevent printing an excess character at termination). If not, we execute an extra instruction to switch to the check edge.

If Fizz and/or Buzz has been printed, the check edge has a leftover "z" in it, else it is 0. If it is a 0, we execute z{{!"'} which puts a z in the check edge and prints the number before returning to the check edge and executing the check again. Now the check edge has a "z" in it no matter what, so we branch to the ?{}g4; which prints a newline.

Finally, d'% checks if the number is divisible by 100. If so, it terminates. Otherwise, it moves to the start of the loop.

| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Go, 130 129 134 bytes

package main;import."fmt";func main(){for i:=1;i<101;i++{o:="";if i%3<1{o+="Fizz"};if i%5<1{o+="Buzz"};if o==""{Print(i)};Println(o)}}

I wish i had ternary operators...

Edit: @Dust pointed out that I printed to stderr so my solution actually increased in size :(

Try it online!

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ I think this prints to STDERR which he said is not allowed. \$\endgroup\$ – Dust Apr 19 '18 at 19:14
  • \$\begingroup\$ @Dust you are right, I'll have to revise \$\endgroup\$ – Kristoffer Sall-Storgaard Apr 20 '18 at 7:32
3
\$\begingroup\$

12-BASIC, 73 55 50 bytes

FOR I=1TO 100?"FIZZ"*!(I%3)+"BUZZ"*!(I%5)OR I
NEXT

The first code golf program I've written in the language I'm creating.
I should probably avoid code golf while working on it though...

| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

MathGolf, 24 22 bytes

♀{î╕Σ╠δ╕┌╠δ`+Γî35α÷ä§p

Try it online!

Explanation

♀                         Push 100
 {                        Start block
  î                       Push loop counter (1-indexed)
   ╕Σ╠δ                   Decompress "Σ╠" and capitalize to get "Fizz"
       ╕┌╠δ               Decompress "┌╠" and capitalize to get "Buzz"
           `              Duplicate top 2 elements of stack
            +             Add (creating "fizzbuzz")
             Γ            Wrap top 4 elements of stack in array
              î           Push loop counter (1-indexed)
               3          Push 3
                5         Push 5
                 α        Wrap last 2 elements in array
                  ÷       Check divisibility (implicit mapping)
                   ä      Convert from binary to int
                    §     Get array item
                     p    print
                          End block on code end, for loop implicit (100 iterations)
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ @dzaima Darn, I forgot about that completely. I have however had a capitalization operator in mind for a while. That should add one byte to the solution, but it is not yet implemented. \$\endgroup\$ – maxb Sep 12 '18 at 19:33
  • \$\begingroup\$ I fixed the capitalization, at the cost of two bytes. \$\endgroup\$ – maxb Sep 13 '18 at 6:58
3
\$\begingroup\$

Julia 1.0, 72 bytes

(n->println([n,"Fizz","Buzz","FizzBuzz"][sum(n.%[1,3,5,5].<1)])).(1:100)

Not the shortest solution possible, but I like the obfuscation. Try it online!

Explanation

We apply an anonymous function (n->...) itemwise .( ) to the range 1:100.

The function body does this (using sample input n=5):

n.%[1,3,5,5]          # Modulo n by each of these numbers                     [0,2,0,0]
.<1                   # Itemwise, is each remainder zero?                     [true,false,true,true]
sum(  )               # Count number of trues in the array                    3
                      # This will be 4 for multiples of 15, 3 for multiples
                      # of 5, 2 for multiples of 3, and 1 for other numbers
[n,"F","B","FB"][  ]  # Index (1-based) into this array                       "Buzz"
println(  )           # Print, with a newline
| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Javascript, 80 bytes

for(i=1;i<101;i++){console.log(i%3==0?i%5==0?"FizzBuzz":"Fizz":i%5==0?"Buzz":i)}
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ To whoever downvoted this; you really should explain why. Especially considering Jey is a new contributor. \$\endgroup\$ – Marie Feb 27 '19 at 19:27
3
\$\begingroup\$

Word VBA, 124 189 bytes

Sub f()
For i=1 To 100
r=""
If i Mod 3=0 Then r="Fizz"
If i Mod 5=0 Then r=r & "Buzz"
If r="" Then r=i
Debug.?r
Next
End Sub

The code breakdown is fairly simple (yay, BASIC).

  1. Loop from 1 to 100

    For i=1 To 100
    
  2. Set a variable to be an empty string

    r=""
    
  3. Check the value on the counter to see if we should set the variable to Fizz

    If i Mod 3=0 Then r="Fizz"
    
  4. Check the counter to see if we need to add Buzz (adding it to an empty string is the same as setting that variable to Buzz)

    If i Mod 5=0 Then r=r & "Buzz"
    
  5. Check to see if the variable is still empty and therefore needs to be set to the counter value

    If r="" Then r=i
    
  6. Prints the results to the immediate window

    t = t & r & vbCr
    

EDIT: Used @Taylor-Scott's suggestions to tighten it up. Relies on the meta discussion about counting characters when your IDE forces whitespace. Specifically the conclusion that if you can paste the code from the answer into the IDE and run it without issues, then you don't have to count the results of autoformatting.

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Actually, the spacing after paragraphs is just a display thing. The plain text output will not have this spacing. :-) If you could add a code breakdown and explanation, this would have my upvote. \$\endgroup\$ – wizzwizz4 Apr 22 '16 at 16:47
  • \$\begingroup\$ Yes, those are the words I was looking for. Ta! \$\endgroup\$ – phrebh Apr 22 '16 at 17:57
  • \$\begingroup\$ +1, as promised! I have however noticed some irritating spaces around certain operators; can those be removed, or is it a language "feature"? \$\endgroup\$ – wizzwizz4 Apr 22 '16 at 19:15
  • \$\begingroup\$ @wizzwizz4 Unfortunately, those spaces are a limitation of the language. The IDE forces them in there and you can't get around using the IDE. One of the many, many reasons that VBA is not a good candidate for code golf. \$\endgroup\$ – phrebh Apr 25 '16 at 19:03
  • \$\begingroup\$ @phrebh can you write in a non-IDE e.g. notepad++, textedit, etc. and run as VB? \$\endgroup\$ – Rɪᴋᴇʀ May 5 '16 at 21:09
3
\$\begingroup\$

brainfuck, 628 499 bytes

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

This took me WAY too long. It's an extremely naive implementation with two divmods and a printing bit for Fizz and Buzz, as well as an equality check for 100. All in all not really golfed. At all. Not even a little bit. But it was fun, as this was my first ever real brainfuck program.

I started this by purposely not looking at any of the other brainfuck answers, partly so I wouldn't get discouraged, and partly so I wouldn't even subconsciously use any other ideas.

Any feedback or shrinkings are appreciated!

Badly commented source code

Try it online!

| improve this answer | | | | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Some quick golfing; There's some leftover whitespace in the code, and all the [-]s can be replaced with ,s (if you're okay with EOF being 0). At least one of the [-]s isn't necessary. The not of the modulo will probably be shorter with forking the movement instead ([>>]<), making sure the tape ends up the same afterwards \$\endgroup\$ – Jo King Feb 28 '19 at 2:26
  • 1
    \$\begingroup\$ I don't think any of my implementations support EOF as 0, but I am interested in the unnecessary [-] clear cell and the [>>]<. Is there a chance you can suggest an edit? \$\endgroup\$ – ThePlasmaRailgun Feb 28 '19 at 5:35
  • \$\begingroup\$ 596 bytes without whitespace and redundant [-]s. I think you'll find that most implementations use 0 as the EOF, and even the ones that don't usually use -1/255, which is still one byte shorter. I guess there's also no change, but that's rare. I'll work on the [>>]< part \$\endgroup\$ – Jo King Feb 28 '19 at 6:11
  • \$\begingroup\$ 499 bytes. I've changed it to the [>>]< method I mentioned above, and golfed some other parts. I didn't really touch the print as a number part, so you can probably golf something there. \$\endgroup\$ – Jo King Feb 28 '19 at 8:02
3
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 137 121 114 bytes

I	X =X + 1
	O =EQ(REMDR(X,3)) 'Fizz'
	O =O EQ(REMDR(X,5)) 'Buzz'
	O =IDENT(O) X
	OUTPUT =O
	O =LT(X,100) :S(I)
END

Try it online!

Explanation:

					;* uninitialized variables start as ''
					;* which is coerced to 0 in computations
I	X =X + 1			;* Increment X
	O =EQ(REMDR(X,3)) 'Fizz'	;* if X mod 3 == 0, O = 'Fizz'
	O =O EQ(REMDR(X,5)) 'Buzz'	;* if X mod 5 == 0, concatenate O and 'Buzz'
	O =IDENT(O) X			;* if O is IDENTical to the empty string,
					;* set O to X
	OUTPUT =O			;* print O
	O =LT(X,100) :S(I)		;* set O to '' and if X < 100, goto I
END
| improve this answer | | | | |
\$\endgroup\$
3
\$\begingroup\$

Zsh, 105 78 68 66 61 bytes

Try it online!

for i ({1..100})(((i%3))||w=Fizz;((i%5))||w+=Buzz;<<<${w-$i})

-27 using simpler approach
-10 using parameter fallback
-2 thanks to @Dennis - kudos for the bash solution
-5 thanks to @GammaFunction


Original solution, using weird r flag... try it online

for ((;i++<100;));{f=$[i%3>0?0:4] b=$[i%5>0?0:4]
echo ${(r:$f::Fizz:)}${(r:$b::Buzz:)}`((f+b>0))||<<<$i`}
| improve this answer | | | | |
\$\endgroup\$
  • 1
    \$\begingroup\$ You don't need the last ; on the first line. A port to Bash takes 70 bytes, thus beating my answer. \$\endgroup\$ – Dennis Aug 28 '19 at 14:49
  • 1
    \$\begingroup\$ Also, you don't need the newline before the last } (which is missing in your answer). Try it online! \$\endgroup\$ – Dennis Aug 28 '19 at 14:56
  • \$\begingroup\$ the bash solution still wins for originality.. I couldn't port that crazy for expression to zsh \$\endgroup\$ – roblogic Aug 28 '19 at 15:01
  • 1
    \$\begingroup\$ 61, mostly thanks to subshells \$\endgroup\$ – GammaFunction Oct 15 '19 at 2:03
3
\$\begingroup\$

Windows Batch, 149 bytes

@for /l %%N in (1 1 100)do @(set s=&set/a1/(%%N%%3^)||set s=Fizz&set/a1/(%%N%%5^)&&(if defined s (echo Fizz)else echo %%N)||call echo %%s%%Buzz)2>nul

The SET /A statements test the modulo 3 and 5 without using IF by intentionally dividing by zero and using && and || conditional command concatenation. Of course stderr must be disabled, but it still saves bytes vs an IF statement.

Windows Batch (unusual cmd.exe configuration, and environment assumption), 166 165 133 bytes

My original answer used delayed expansion, but the code to enable delayed expansion takes 32 bytes all on its own. However, some people have their cmd.exe configured to have delayed expansion enabled by default. For the small minority of people that configure cmd.exe this way, then the following is significantly shorter.

@for /l %%N in (1 1 100)do @(set 1=&set/a1/(%%N%%3^)||set 1=Fizz&set/a1/(%%N%%5^)||set 1=!1!Buzz&>nul set 1&&echo !1!||echo %%N)2>nul

Besides relying on an unusual cmd.exe configuration, it is also reliant on the absence of any environment variable names that begin with 1. This is normally safe because batch treats something like %1var% as batch parameter %1 followed by a string constant var - the trailing % would get stripped. So people are taught to never begin variable names with a digit.

| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

JavaScript, 73 bytes

for(i=s='';i++<100;s+=((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)+"\n");alert(s)
| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

PHP, 73 71 bytes

<?for($i=0;$i++<100;)echo$i%3?$i%5?$i:@Buzz:@Fizz.($i%5?"":@Buzz),"
";

All the most terrible things. I wanted the wrongheaded ternary to do something magical, but it did not.

| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

Ceylon, 368 144 123 96 bytes

shared void z(){for(i in 1..100){print(["FizzBuzz","Buzz","Fizz",i][(i%5).sign*2+(i%3).sign]);}}

Here we have the ungolfed original of 368 bytes:

shared void fizzBuzz() {
    for(i in 1..100) {
        if(3.divides(i)){
             if(5.divides(i)) {
                 print("FizzBuzz");
             } else {
                 print("Fizz");
             }
        } else {
            if(5.divides(i)) {
                print("Buzz");
            } else {
                print(i);
            }
        }
    }
}

In Ceylon, Integers are also just objects, so one can call methods on them (like the divides method here).

1..100 is syntactic sugar for span(1, 100), which is a Range<Integer>, which implements Iterable<Integer>, and can therefore be used with the for loop.

The print function takes one argument (of type Anything), stringifies it (i.e. if it's an object, calls its .string attribute, if it's null, takes "<null>") and prints it to the standard output.

Removing whitespace, using a shorter function name, and replacing x.divides(y) by the shorter y%x==0, which is essentially how divides is implemented, gives us this (144 bytes):

shared void f(){for(i in 1..100){if(i%3==0){if(i%5==0){print("FizzBuzz");}else{print("Fizz");}}else{if(i%5==0){print("Buzz");}else{print(i);}}}}

Of course, this is not the best which is possible ... this uses print and if much too often, and also does the check for divisibility by 5 twice.

Integers (or Numbers types in general) have also the .sign attribute, which is 1 for positive numbers, 0 for zero, and -1 for negatives. We can use that together with the remainder operator to get a different value for each of the four cases: (i % 5).sign * 2 + (i % 3).sign]. This is 0 for FizzBuzz, 1 for Buzz, 2 for Fizz and 3 for the "plain" case. We can use this as an index of a tuple, coming to this 123-bytes program:

shared void z() {
    for(i in 1..100) {
        print(["FizzBuzz", "Buzz", "Fizz", i][(i%5).sign*2 + (i%3).sign]);
    }
}

([...] is the syntax for both Tuple creation (here a Tuple with element types String, String, String, Integer, formally Tuple<String|Integer, String, Tuple<String|Integer, String, Tuple<String|Integer, String, Tuple<Integer, Integer, Empty>>>, which can be written shorter as [String, String, String, Integer]) and lookup in a Correspondence (and this tuple type implements Correspondence<Integer, String|Integer>).

Removing the whitespace again gives us this 96 byte program:

shared void z(){for(i in 1..100){print(["FizzBuzz","Buzz","Fizz",i][(i%5).sign*2+(i%3).sign]);}}
| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

awk, 62

END{for(x="Fizz";i<100;y="Buzz")print++i%15?i%5?i%3?i:x:y:x y}

Pretty sure there's no surprises here.

Call

awk 'END{for(x="Fizz";i<100;y="Buzz")print++i%15?i%5?i%3?i:x:y:x y}'

then press Ctrl-D to signal end of input.

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ I'm curious if the Ctrl-D should be included in the byte-count. Using a BEGIN block and rearranging the operators a bit adds 1 byte, i.e. BEGIN{for(x="Fizz";i<100;y="Buzz")print++i%3?i%5?i:y:i%5?x:x y} \$\endgroup\$ – Robert Benson May 30 '17 at 16:19
2
\$\begingroup\$

VB.Net, 147 146 bytes

Module F
Sub Main()
For i=1To 100
Dim a=i Mod 3,b=i Mod 5
Console.WriteLine("{0:#}{1:;;Fizz}{2:;;Buzz}",If(a*b>0,i,0),a,b)
Next
End Sub
End Module

It uses the same conditional formatting trick as the C# answer by Pierre-Luc Pineault.

UPDATED: saved 1 byte thanks to Brian J

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ you can save a byte by using If instead of IIf. The difference is that IIf is a function that will evaluate both the true and false options, while If is an operator that will only evaluate the option it needs. Functionally doesn't make a difference in this case, but does save a character. \$\endgroup\$ – Brian J Sep 25 '15 at 13:13
2
\$\begingroup\$

haxe, 110 bytes

class Main{
  static function main()
    for(i in 1...101)
      Sys.println(i%3<1?"Fizz"+(i%5<1?"Buzz":""):i%5<1?"Buzz":i);
}

(newlines and indents added for clarity)

Haxe isn't much of a golfing language … I was trying to do something with enumerators:

class Main{
  static function main()
    for(i in 1...101)
      Sys.println(
        switch(i){
          case _%3=>0:i%5<1?"FizzBuzz":"Fizz";
          case _%5=>0:"Buzz";
          case _:i;
        }
      );
 }

But 140 bytes. :I

| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

O, 53 52 bytes

I'm sure that there will be a better way to do this. Thanks to kirbyfan64sos for the implicit J.

"Buzz"JA.*1mrl{.3%{.5%{}{;J}?}{"Fizz"\5%{}{J+}?}?p}d

Try it here

| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ 52 bytes: "Buzz"JA.*1mrl{.3%{.5%{}{;J}?}{"Fizz"\5%{}{J+}?}?p}d. O has the implicit J variable like Pyth. \$\endgroup\$ – kirbyfan64sos Oct 1 '15 at 23:13
  • \$\begingroup\$ omg someone other than my mom used O <3 \$\endgroup\$ – phase Nov 8 '15 at 4:09
2
\$\begingroup\$

Swift, 75 bytes

for n in 1...100{print(n%3*n%5>0 ?n:(n%3>0 ?"":"Fizz")+(n%5>0 ?"":"Buzz"))}
| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

F#, 129 116 113 111

Seq.iter(fun x->printfn"%s"(["Fizz";"";""].[x%3]+(if x%5=0 then"Buzz"elif x%3>0 then string x else""))){1..100}
| improve this answer | | | | |
\$\endgroup\$
2
\$\begingroup\$

D, 130 bytes

import std.stdio,std.conv;void main(){string x;for(int i;i++<100;x=((i%3?"":"Fizz")~(i%5?"":"Buzz")),writeln(x?x:i.to!string)){};}

Ungolfed:

module FizzBuzz;

import std.stdio;
import std.conv;

void main() {
  string x;
  for (
    int i;
    i++ < 100;
    x = ((i % 3 ? "" : "Fizz")
      ~ (i % 5 ? "" : "Buzz")),
    writeln(x ? x : i.to!string)
  ){};
}

Or, building a string, for 142 bytes,

import std.stdio,std.conv;void main(){string x,y;for(int i;i++<100;x=((i%3?"":"Fizz")~(i%5?"":"Buzz")),y~=(x?x:i.to!string)~"\n"){};write(y);}

Ungolfed:

module FizzBuzz;

import std.stdio;
import std.conv;

void main() {
  string x,y;
  for (
    int i;
    i++ < 100;
    x = ((i % 3 ? "" : "Fizz")
      ~ (i % 5 ? "" : "Buzz")),
    y ~= (x ? x : i.to!string) ~ "\n"
  ){};
  write(y);
}
| improve this answer | | | | |
\$\endgroup\$
1 2 3
4
5
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.