196
\$\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
    Sep 24, 2015 at 20:47
  • 1
    \$\begingroup\$ @AShelly Only when running \$\endgroup\$
    – Beta Decay
    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
    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
    Sep 25, 2015 at 0:50
  • 76
    \$\begingroup\$ A "vanilla fizzbuzz" sounds delicious. \$\endgroup\$ Sep 25, 2015 at 15:12

416 Answers 416

1
2
3 4 5
14
13
\$\begingroup\$

Vim, 44 bytes

33o<CR>Fizz<CR><Esc>qqABuzz<Esc>5kq19@q:%s/^$/\=line('.')<CR>

On vimgolf.com we have the classic Remember FizzBuzz?, which is similar to this, but keeps the numbers on all the lines. There's also Neither Fizz nor Buzz, which uses a similar format, but provides a useful input file. Those small differences drastically change the optimal solution. I did exactly this same variation 2 years ago in the edit to this reddit post. I had to check whether visual increment (not available back then) creates an improvement, like it has for the other variations, but it looks like it hasn't.

  • 33o<CR>Fizz<CR><Esc>: Create the Fizz lines AND the blank lines with a simple insert mode repeat. Much quicker than a macro. AFAIK first discovered by @KersonHsiao in the vimgolf.com version, and used by every top solution since.
  • qqABuzz<Esc>5kq19@q: A very simple macro appends the Buzzes.
  • :%s/^$/\=line('.')<CR>: Replaces all blank lines with that line's line number. The expression replacement is very long, so this tactic is rarely used in vimgolf, but the alternatives are all worse.
\$\endgroup\$
13
\$\begingroup\$

R, 88 83 77 71 70 bytes

I'm sure that this can be improved ... and it was with credit to @flodel. A further couple of bytes saved thanks to a suggestion from @njnnja and another from @J.Doe

x=y=1:100;y[3*x]='Fizz';y[5*x]='Buzz';y[15*x]='FizzBuzz';write(y[x],1)
\$\endgroup\$
7
  • \$\begingroup\$ A cat answer. The mouse is above :) \$\endgroup\$ Sep 25, 2015 at 10:36
  • 2
    \$\begingroup\$ I found a bit better: x=1:100;i=!x%%3;j=!x%%5;x[i]="Fizz";x[j]="Buzz";x[i&j]="FizzBuzz";cat(x,sep="\n") \$\endgroup\$
    – flodel
    Sep 28, 2015 at 2:13
  • \$\begingroup\$ @njnnja Thanks for the suggestion. I implemented it with a write rather than cat though \$\endgroup\$
    – MickyT
    Sep 28, 2015 at 19:07
  • 2
    \$\begingroup\$ Necromancy here! The write call can take a 1 instead of a an empty string so x=y=1:100;y[3*x]='Fizz';y[5*x]='Buzz';y[15*x]='FizzBuzz';write(y[x],1) is a trivial 1 byte golf for 70 bytes. \$\endgroup\$
    – J.Doe
    Oct 1, 2018 at 13:00
  • \$\begingroup\$ 68 bytes. The bytecount includes three unprintable backspaces, and it doesn't work correctly in TIO. \$\endgroup\$
    – J.Doe
    Oct 4, 2018 at 21:41
12
\$\begingroup\$

PHP, 54 bytes

<?for(;$i++<100;)echo[Fizz][$i%3].[Buzz][$i%5]?:$i,~õ;

Valid for v5.5 onwards. The õ is character 245, a bit inverted \n.

I assume the default interpreter settings, as they are without any ini. If you are uncertain, you may disable your local ini with -n as in php -n fizzbuzz.php.

A version which will run error-free with absolutely any configuration file is 62 bytes:

<?php
for(;$i++<100;)echo@([Fizz][$i%3].[Buzz][$i%5]?:$i),"
";
\$\endgroup\$
7
  • \$\begingroup\$ The STFU operator @ does not necessarily mean that the code is error free. \$\endgroup\$
    – sitilge
    Sep 28, 2015 at 12:42
  • \$\begingroup\$ ideone.com/5rfNt0 \$\endgroup\$
    – Kzqai
    Sep 30, 2015 at 6:55
  • \$\begingroup\$ @Kzqai ideone.com/0zRA9e short_open_tag is off, E_NOTICE is on. Neither of these are default settings. \$\endgroup\$
    – primo
    Sep 30, 2015 at 11:46
  • \$\begingroup\$ I'm getting a bunch of errors on 3v4l.org \$\endgroup\$
    – a coder
    Jan 27, 2016 at 23:42
  • \$\begingroup\$ @acoder relevant meta post. 3v4l.org seems useful. \$\endgroup\$
    – primo
    Jan 28, 2016 at 9:32
12
\$\begingroup\$

80386 machine code + DOS, 75 bytes

Hexdump of the code:

0D 0A 24 B1 64 33 C0 BA-03 05 BB 00 01 40 50 FE
CE 75 0C 83 EB 04 66 C7-07 42 75 7A 7A B6 05 FE
CA 75 0C 83 EB 04 66 C7-07 46 69 7A 7A B2 03 84
FF 74 0C D4 0A 04 30 4B-88 07 C1 E8 08 75 F4 52
8B D3 B4 09 CD 21 5A 58-E2 C0 C3

Source code (TASM syntax):

    .MODEL TINY

    .CODE
    .386
    org 100h

MAIN PROC
    db 13, 10, '$'
    mov cl, 100
    xor ax, ax
    mov dx, 503h

main_loop:
    mov bx, 100h
    inc ax
    push ax

    dec dh
    jnz short buzz_done
    sub bx, 4
    mov dword ptr [bx], 'zzuB'
    mov dh, 5
buzz_done:

    dec dl
    jnz short fizz_done
    sub bx, 4
    mov dword ptr [bx], 'zziF'
    mov dl, 3
fizz_done:

    test bh, bh
    jz short num_done

decimal_loop:
    aam;
    add al, '0'
    dec bx
    mov [bx], al
    shr ax, 8
    jnz decimal_loop

num_done:
    push dx
    mov dx, bx;
    mov ah, 9
    int 21h
    pop dx
    pop ax

    loop main_loop
    ret

MAIN ENDP
    END MAIN

This code counts from 1 to 100 in ax, building the output message from the end to the beginning. The end of the message (newline and the $ character that DOS uses for end-of-message flag) appears at the beginning of the code:

db 10, 10, '$'

It's executed as a harmless instruction (or ax, 240ah). I could put it in a more conventional place, like after the end of the code, but having it at address 0x100 has a benefit.

The code also uses 2 additional counters:

  • Counting from 3 to 0 in dl
  • Counting from 5 to 0 in dh

When a counter reaches 0, it pushes the string Fizz or Buzz to the end of the output message. If this happens, bx will be decreased, and bh will be zero. This is used as a condition for outputting the number in a decimal form.

Note: I am using 32-bit data here. This won't work on a pre-386 computer.

\$\endgroup\$
3
  • \$\begingroup\$ Does TASM really handle multi-byte characters constants in the opposite order from NASM? In NASM, you write mov [mem], 'Fizz' to store Fizz in that order in memory, matching db directives. See my overcomplicated "efficient" YASM FizzBuzz for example. \$\endgroup\$ May 28, 2016 at 0:36
  • 1
    \$\begingroup\$ Does it save any bytes to use std, then stosb / stosd? You'd have to replace test bh,bh with cmp di, 100h or something. Instead of saving/restoring the counter in AL, you could keep it in BL and just clobber eax whenever you want. E.g. sub bx, 4 / mov dword ptr [bx], 'zzuB' is 3+7 bytes, right? mov eax, 'zzuB' / stosd is 6+2 bytes (operand-size prefix on both). It would be nice if the answer included disassembly so instruction sizes were visible. \$\endgroup\$ May 28, 2016 at 0:46
  • 1
    \$\begingroup\$ This is a great answer - abusing benign instructions for data and using never-used PSP memory space. @PeterCordes I played with your suggestions using stosd but wasn't able to eek out any score reduction myself. Since stosd decrements DI afterwards you don't get to lose the sub di, 4 and then you have DI 4 bytes off at the end. I was able to -6 bytes using a few other minor tweaks which I ended up posting as a separate answer (only because I couldn't possibly fit in all a comment). Kudos! \$\endgroup\$
    – 640KB
    Aug 27, 2019 at 17:19
11
\$\begingroup\$

JavaScript, 65 bytes

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

The shortest approach I've found yet. Perhaps there's a better one; suggestions are welcome. This was originally flagged ES6, but this works in ES5, and to my knowledge there's not a shorter way with ES6 features.

Here's another attempt, using .slice and some complicated maths for a total of 66 bytes:

for(i=0;i++<100;console.log('FizzBuzz'.slice(i%3&&4,i%5?4:8)||i));

(Thanks to Ben Fortune for a couple of handy tricks!)

\$\endgroup\$
4
  • 2
    \$\begingroup\$ You could shorten your second attempt to for(i=0;i++<100;console.log('FizzBuzz'.slice(i%3&&4,i%5?4:8)||i)); \$\endgroup\$ Sep 25, 2015 at 10:13
  • \$\begingroup\$ If you move console.log(...) outside for(...;...;...), you can drop the semicolon. \$\endgroup\$
    – Dennis
    Oct 3, 2015 at 15:54
  • \$\begingroup\$ This is old, but ES6 plus Dennis= 61 bytes: for(i=0;i++<100;)console.log(i%3?i:'fizz'+${i%5?'':'Buzz'}) I can't make it a code block because the template string won't show up correctly \$\endgroup\$ Nov 15, 2015 at 18:23
  • \$\begingroup\$ @GenericUser That doesn't quite work; it never prints Buzz by itself. To insert code with backticks in it, just use 2 or 3 backticks on each end. \$\endgroup\$ Nov 15, 2015 at 18:31
11
\$\begingroup\$

dc, 64 62 bytes

[[Fizz]P]sI[[Buzz]P]sU[dn]sNz[zdd3%d0=Ir5%d0=U*0<NAPz9B>L]dsLx

Ungolfed:

[[Fizz]P]sI  # macro I: print "Fizz"
[[Buzz]P]sU  # macro U: print "Buzz"
[dn]sN       # macro N: print current stack depth

z            # increase stack depth

[            # Begin macro
  zdd           # Get current stack depth and ducplicate it twice
  3%d0=I        # Check modulo 3 and leave a duplicate. If it's 0, run macro I
  r             # Rotate top two elements, bringing up the stack depth again
  5%d0=U        # Check modulo 5 and leave a duplicate. It it's 0, run macro U
  *             # Multiply the duplicates of modulos of 3 and 5 ...
  0<N           # ... if it's not 0, run macro N
  AP            # Print a newline (`A` is 10)
                # The macro leaves the stack with one more element each time
  z9B>L      # Run macro L if stack depth is less than "ninety eleven" (101)
]         # End macro

dsLx  # store the macro in register L and execute it
\$\endgroup\$
11
\$\begingroup\$

Lua, 72 bytes

for i=1,100 do print(({'FizzBuzz','Buzz','Fizz',i})[i^2%3+i^4%5*2+1])end

Tied the world record! (Please don't cheat the rankings there.)

\$\endgroup\$
4
  • \$\begingroup\$ I stole this technique for my AppleScript answer. \$\endgroup\$
    – kernigh
    Oct 25, 2017 at 2:38
  • 3
    \$\begingroup\$ Cool answer. My 72 was for x=1,100 do print(({x,[0]="FizzBuzz",[6]="Fizz"})[x^4%15]or"Buzz")end, but looking at yours, I saw this 70: for x=1,100 do print(({"FizzBuzz",x,[7]="Fizz"})[1+x^4%15]or"Buzz")end \$\endgroup\$
    – tehtmi
    Jul 18, 2018 at 23:34
  • \$\begingroup\$ @tehtmi Oh, that’s so nifty! \$\endgroup\$
    – Lynn
    Jul 21, 2018 at 15:34
  • \$\begingroup\$ 67 bytes... code.golf/rankings/holes/fizz-buzz/lua/bytes \$\endgroup\$ May 3, 2022 at 1:58
11
\$\begingroup\$

80386 machine code + DOS, 75 68 bytes

NOTE: This is a reply to @anatolyg's really clever 2015 answer, with a few tweaks to reduce the score by 7 bytes. I'm only submitting this as a separate answer because it wouldn't be possible to explain fully in a comment.

Changes:

  • Use SI to reset BX since DOS sets SI initially to 100H (ref) instead of an imm. (-1 byte)
  • Instead of using a 3/5 counter in DH/DL, use AAM for modulo operations on counter. AAM is a 2 byte instruction that's effectively a byte-length DIV that can accept an imm value as the divisor and also sets ZF if AL mod n = 0. @Peter Cordes touches on this in his very brilliant post about FizzBuzz in assembly. (-5 bytes)
  • Instead of CR/LF, use LF/CR (the order doesn't matter to DOS). This translates to an instruction that does not modify the startup value of AX (in fact it zeroes out AL) so we can eliminate the xor ax,ax and save two bytes. It does come at a cost because 0A 0D is only a two-byte instruction so the rest of the 24xx instruction needs to be padded with one more byte. (-1 byte)

Unassembled:

0A 0D           or cl, [di]             ; LF and CR bytes (newline)
24 00           and al, 0               ; DOS string delim ('$') + pad byte
B1 64           mov cl, 100             ; set loop counter to 100 
                 
            main_loop: 
8B DE           mov bx, si              ; init bx to 100h 
40              inc ax                  ; increment fizzbuzz counter 
50              push ax                 ; save fizzbuzz counter
                                     
50              push ax                 ; save ax from getting clobbered by AAM 
D4 05           aam 5                   ; AL = AL mod 5, ZF if AL = 0
58              pop ax                  ; restore ax 
75 0A           jnz short buzz_done     ; jump if not a 'Fizz'
83 EB 04        sub bx, 4               ; offset for output string 
66C707 7A7A7542 mov dword ptr [bx], 'zzuB' 
            buzz_done: 
                 
50              push ax 
D4 03           aam 3                   ; AL = AL mod 3, ZF if AL = 0
58              pop ax 
75 0A           jnz short fizz_done     ; jump if not a 'Buzz'
83 EB 04        sub bx, 4 
66C707 7A7A6946 mov dword ptr [bx], 'zziF' 

            fizz_done: 

84 FF           test bh, bh             ; either a Fizz or a Buzz? (BX not changed)
74 0C           jz short num_done       ; if so, do not display a digit
                 
            decimal_loop: 
D4 0A           aam;                    ; AL = AL mod 10
04 30           add al, '0'             ; convert to ASCII
4B              dec bx 
88 07           mov [bx], al 
C1 E8 08        shr ax, 8               ; 'mov al, ah', ZF if AL = 0
75 F4           jnz decimal_loop 
                 
            num_done: 
8B D3           mov dx, bx              ; set dx to output string pointer
B4 09           mov ah, 9 
CD 21           int 21h 
58              pop ax                  ; restore fizzbuzz counter
                 
E2 C3           loop main_loop 
C3              ret 

xxd binary:

00000000: 0a0d 2400 b164 8bde 4050 50d4 0558 750a  [email protected].
00000010: 83eb 0466 c707 4275 7a7a 50d4 0358 750a  ...f..BuzzP..Xu.
00000020: 83eb 0466 c707 4669 7a7a 84ff 740c d40a  ...f..Fizz..t...
00000030: 0430 4b88 07c1 e808 75f4 8bd3 b409 cd21  .0K.....u......!
00000040: 58e2 c3c3                                X...
\$\endgroup\$
1
  • 6
    \$\begingroup\$ Of course it's a competing answer! It has nice ideas. Competition of this kind is exactly what this site needs! \$\endgroup\$
    – anatolyg
    Aug 27, 2019 at 22:47
11
\$\begingroup\$

Bash, 58 bytes

eval i={1..100}';a=([i%3]=Fizz [i%5]+=Buzz);echo ${a-$i};'

Try it online!

\$\endgroup\$
2
  • 3
    \$\begingroup\$ 7 people have copied this solution verbatim, but only 3 upvotes? Have another. \$\endgroup\$
    – primo
    Mar 13, 2021 at 7:20
  • 2
    \$\begingroup\$ Not assigning i saves one: eval {0..99}';a=([++i%3]=Fizz [i%5]+=Buzz);echo ${a-$i};' \$\endgroup\$
    – primo
    Nov 24, 2021 at 9:34
10
\$\begingroup\$

Julia, 64 bytes

for i=1:100 x="Fizz"^(i%3<1)*"Buzz"^(i%5<1);println(x>""?x:i)end
\$\endgroup\$
10
\$\begingroup\$

Bubblegum, 131 129 bytes

0000000: 4d cd bb 0d c4 30 0c 03 d0 9e db e8 63 7d da 14 d9 e5  M....0......c}....
0000012: 06 b8 26 d3 e7 60 0b 38 56 a6 29 10 4f a0 b8 3f cf 03  ..&..`.8V.).O..?..
0000024: c7 f5 fd 3d 3b 27 ea 84 5d 89 9c 8f 18 c4 77 3c 75 40  ...=;'..].....w<u@
0000036: 72 2e 4d 63 55 a8 d1 5c 63 fa 82 f6 7f 6e 02 1b da d8  r.McU..\c....n....
0000048: b6 84 b1 ee a3 bb c1 49 f7 80 8f ee ac 2f c5 62 7d 8d  .......I...../.b}.
000005a: be 0a 8b f4 10 c4 e8 c1 7a 24 82 f5 1c 3d 0d 49 7a 06  ........z$...=.Iz.
000006c: 72 f4 64 bd 14 c5 7a 8d 5e 85 22 bd 05 3d 7a b3 de 89  r.d...z.^."..=z...
000007e: 26 fd 05                                               &..

The above hexdump can be reversed with xxd -r -c 18 > fizzbuzz.bg.

Compression has been done with Python's zlib, which uses the DEFLATE format but obtains a better ratio than (g)zip.

Thanks to @Sp3000 for -2 bytes!

\$\endgroup\$
2
  • 29
    \$\begingroup\$ You could golf off about 43 bytes by breaking SHA-256. \$\endgroup\$
    – lirtosiast
    Sep 25, 2015 at 0:07
  • 1
    \$\begingroup\$ @ThomasKwa: sounds easy. \$\endgroup\$ Sep 25, 2015 at 22:41
10
\$\begingroup\$

Python 2, 61 60 bytes

for i in range(1,101):print"Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i
\$\endgroup\$
7
  • \$\begingroup\$ This is invalid: it prints 0 at the start \$\endgroup\$
    – Beta Decay
    Sep 24, 2015 at 19:38
  • 1
    \$\begingroup\$ You could use either i+1 or range(1,101) to fix it. \$\endgroup\$ Sep 24, 2015 at 19:40
  • \$\begingroup\$ Now it only goes up to 99. \$\endgroup\$
    – Zach Gates
    Sep 24, 2015 at 19:48
  • 2
    \$\begingroup\$ the output is also straight up incorrect. 89 prints out a FizzBuzz whereas 90 is printed as 90 \$\endgroup\$
    – Kevin W.
    Sep 24, 2015 at 19:50
  • 3
    \$\begingroup\$ Have you actually tested this program? \$\endgroup\$
    – Beta Decay
    Sep 24, 2015 at 19:57
10
\$\begingroup\$

TrumpScript, 938 bytes

As always nothing is, 1000001 minus 1000000;
And Putin is, 1000003 minus 1000000; great
Just as Trump is, 1000005 minus 1000000; even better
Also as America is, Putin times Trump; the best
Most importantly Ivanka is, 1000101 minus 1000000;
And believe me that Hillary is nothing
As long as, Hillary thinks less of Ivanka;:
China is friends with Hillary
Democrats are idiots like Hillary
Obama is in line with Hillary
As long as, China thinks its more than America;:
Make China, China minus America;!
As long as, Democrats fear more Trump;:
Make Democrats, Democrats minus Trump;!
As long as, Obama gets more arsenal against Putin;:
Make Obama, Obama minus Putin;!
If everybody thinks, America is China?;:
Say "FizzBuzz"!
Otherwise: if we ask, Democrats are Trump?;:
Say "Buzz"!
Otherwise: what if, Obama is Putin?;:
Say "Fizz"!
Otherwise do this: tell Hillary all her lies!!!
Hillary is, as always Hillary plus nothing;!
America is great.

Try it online!

I was quite bored... Not too efficient, but fun!

Pseudocode:

var nothing = 1, Putin = 3, Trump = 5, America = Putin * Trump, Ivanka = 101, Hillary = nothing;
while Hillary < Ivanka
    var China = Democrats = Obama = Hillary;
    while China > America
        China = China - America;
    while Democrats > Trump
        Democrats = Democrats - Trump;
    while Obama > Putin
        Obama = Obama - Putin;
    if China == America
        print "FizzBuzz";
    else if Democrats == Trump
        print "Buzz";
    else if Obama == Putin
        print "Fizz";
    else
        print Hillary;
    Hillary = Hillary + nothing;
America is great.
\$\endgroup\$
10
\$\begingroup\$

R, 68 66 bytes

for(i in 1:100)write(max(i,paste0("Fizz"[!i%%3],"Buzz"[!i%%5])),1)

I must be missing something here because this is way too simple. I know that you really shouldn't use loops in R but like this is a bit smaller than the first R one I saw so yeah.

Edited about a day after the original: you can get rid of the curly braces to save 2 characters.

\$\endgroup\$
3
  • 4
    \$\begingroup\$ Welcome to Code Golf StackExchange, nice first answer. (It's also the winning R answer here!) \$\endgroup\$
    – user92069
    Jul 17, 2020 at 10:34
  • \$\begingroup\$ @Third-party'Chef' Damn, it's incredible that it took five years for the shortest R solution to be found \$\endgroup\$
    – Beta Decay
    Jul 24, 2020 at 13:26
  • \$\begingroup\$ Eh, don't count it as the shortest ever. Some crazy guy will find some way to make something smaller haha \$\endgroup\$
    – zydras
    Jul 24, 2020 at 18:11
10
\$\begingroup\$

Common Lisp, 123 116

(dotimes(i 100)(loop for(m s)in'((3"Fizz")(5"Buzz"))if(=(mod(1+ i)m)0)do(princ s))(do()((fresh-line))(princ(1+ i))))

Pretty-printed

(dotimes (i 100)
  (loop for (m s) in '((3 "Fizz") (5 "Buzz"))
        if (= (mod (1+ i) m) 0)
        do (princ s))
  (do () ((fresh-line)) (princ (1+ i))))

The do/fresh-line trick

The inner loop iterates over ((3 "Fizz") (5 "Buzz")) for each i and, according to the result of the two consecutive mod operations, eventually prints:

  • nothing
  • or Fizz
  • or Buzz
  • or FizzBuzz

fresh-line is a nice little function that as far as I know is only found in Common Lisp. It adds a newline only if necessary, and returns T only when the newline was added. For the above situations, according to whether we printed something or not, the return values of (fresh-line) are thus respectively:

  • NIL
  • T
  • T
  • T

So I know that the integer must be printed only when we did not print a fresh-line. But if I print the integer, I must also print a newline after it. That's why there is a DO.

DO is a basic yet looping construct that iterates until a condition is met. Here, the condition is the return value of (fresh-line). It it tested before each iteration of the body of the loop, notably the first one. So if the test returns T, then we exit the DO. Otherwise, we execute the body, which prints the integer. Then, we execute the test once again and this time, it returns T because current line is "dirty" (there is an integer printed now).

\$\endgroup\$
3
  • \$\begingroup\$ Clever! I don't think I can change my CL answer to beat it. \$\endgroup\$
    – nanny
    Sep 25, 2015 at 16:42
  • \$\begingroup\$ @nanny If that can comfort you, I don't think I can either. I saw your answer, it was hard to beat. \$\endgroup\$
    – coredump
    Sep 25, 2015 at 16:47
  • \$\begingroup\$ Great answer. I learnt some from it and don't understand it fully yet. However I think I've managed to beat you by 13 bytes using different method. \$\endgroup\$
    – user65167
    Feb 17, 2017 at 22:45
9
\$\begingroup\$

Japt, 45 44 43 39 36 35 33 32 31 bytes

Japt is a shortened version of JavaScript.

Lò1@"Fizz"pXv3)+"Buzz"pXv5)ªX÷

Try it online!

How it works

Lò1@"Fizz"pXv3)+"Buzz"pXv5)ª XÃ ·
Lò1@"Fizz"pXv3)+"Buzz"pXv5)||X} qR

Lò1       // Create the inclusive array [1...100].
@         // Map each item X in this range to:
 "Fizz"p  //  "Fizz" repeated:
  Xv3)    //   if X is divisible by 3, 1 time, otherwise, 0 times;
 +        //  concatenated with
 "Buzz"p  //  "Buzz" repeated:
  Xv5)    //   if X is divisible by 5, 1 time, otherwise, 0 times.
 ||X      //  If the result is an empty string, set it to X.
} qR      // Join the range with newlines.
          // Implicit: output last expression

Old version, 32 bytes:

Lo@"FizzBuzz"s°X%3©4X%5?4:8 ªX÷
Lo@"FizzBuzz"s++X%3&&4X%5?4:8 ||X} qR

Lo            // Create the range [0..100).
@             // Map each item X in this array to:
 "FizzBuzz"s  //  "FizzBuzz".slice(
  ++X%3&&4    //   if ++X is divisible by 3, 0; else, 4,
  X%5?4:8     //   if X is divisible by 5, 8; else, 4).
 ||X          //  If the result is an empty string, set it to X.
} qR          // Join the range with newlines.
              // Implicit: output last expression

Alternate version (45 44 40 38 bytes): (Note: this doesn't work in the current version of Japt)

1o#e £(X%3?":Fizz" +(X%5?":Buzz" ªX} ·
1o#e m@(X%3?":Fizz" +(X%5?":Buzz" ||X} qR

1o#e          // Create an array of 1 to 100.
m@            // Map each item X in this array to:
 (X%3?":Fizz" //  If X is divisible by 3, "Fizz"; else, an empty string
 +            //  concatenated to:
 (X%5?":Buzz" //  if X is divisible by 5, "Buzz"; else, an empty string.
 ||X          //  If the result is an empty string, set it to X.
} qR          // Join the range with newlines.
              // Implicit: output last expression

Suggestions welcome!

\$\endgroup\$
8
\$\begingroup\$

Bash + coreutils, 41 bytes

seq 100|sed 5~5cBuzz|sed 3~3s/[^B]*/Fizz/

You can't seem to do better without cheating: the 12-byte answers on that server simply invoke its gs2 interpreter with a 1-byte FizzBuzz program...

\$\endgroup\$
8
\$\begingroup\$

Brainfuck, 425 bytes

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

Try it online!

Explanation

Cell indexes in comments are in hexadecimal to match numbering in bfdev debug view.

# #####################
# ##### VARIABLES #####
# #####################

# C1 & C2: 48 (ascii 0)
-[>+>+<<-----]>--->-->
# C3: 10 (ascii LF)
++++++++++>
# C4: Singles counter
->
# C5: Tens counter
++++++++++>
# C6: is1to9 if countdown
+++++++++>
# C7: 0 to enter/exit is1to9, or 1 to enter is10to99
>
# C8: 0 to not enter is10to99
>
# C9: isMultiOf3 if countdown
+++>
# CA: 0 to exit isMultiOf3, or 1 to enter !isMultiOf3
>
# CB: 0 to not enter !isMultiOf3
>
# CC: isMultiOf5 if countdown
+++++>
# CD: 0 to exit isMultiOf5, or 1 to enter !isMultiOf5
>
# CE: 0 to not enter !isMultiOf5
>
# CF: 70 F, and put C13 to 70
>>-[<+<+>>-------]<---<--->
# C10: 66 - ascii B
---->
# C11: 105 - ascii i
>-[<++>-----]<+++>
# C12: 122 - ascii z, and put C16 to 122
>>----[<+++<+++>>--]<
# C13: 117 - ascii u
-----
# Goto C5
<<<<<<<<<<<<<<

# #################
# ##### LOGIC #####
# #################

# While C5 (tens counter): Print 1-99
[
# Restore C4: singles counter
  <++++++++++
# For 0 to 9, using singles counter
  [
#   Goto C6
    >>
#   If is1to9
    [
#     Decrement is1to9 countdown
      -
#     Prepare else condition at C8
      >>-<
    ]
#   Goto C7 or C8
    >+
#   Else If C7: is10to99
    [
#     Decrement C7
      -
#     Goto CC
      >>>>>-
#     If is not multi of 5
      [
#       Goto C9
        <<<-
#       If is not multi of 3
        [
#         Print C1: tens
          <<<<<<<<.
#         Prepare else condition at CB
          >>>>>>>>>>-
#         Goto CA
          <
        ]
#       Goto CA or CB
        >+
#       Else If is multi of 3
        [
#         Goto CA, restore, goto CB
          ->
        ]
#       Goto C9 and restore
        <<+
#       Prepare else condition at C1E
        >>>>>-
#       Goto C1D
        <
      ]
#     Goto CD or CE
      >+
#     Else If is multi of 5
      [
#       Goto CD, restore, goto CE
        ->
      ]
#     Goto CC and restore
      <<+
#     Goto C8
      <<<<
    ]
#   Goto C9
    >-
#   If is not multi of 3
    [
#     Goto CC
      >>>-
#     If is not multi of 5
      [
#       Print C2: singles
        <<<<<<<<<<.
#       Prepare else condition at CE
        >>>>>>>>>>>>-
#       Goto CD
        <
      ]
#     Goto CD or CE
      >+
#     Else If is multi of 5
      [    
#       Goto CD, restore, goto CE
        ->
      ]
#     Goto CC and restore
      <<+
#     Prepare else condition at CB
      <-
#     Goto CA
      <
    ]
#   Goto CA or CB
    >+
#   Else If is multi of 3
    [
#     Print Fizz
      >>>>>.>>.>..
#     Goto C9 (If is not multi of 3)
      <<<<<<<<<
#     Restore C9
      +++
#     Goto CA, decrease, goto CB
      >->
    ]
#   Goto CC
    >-
#   If is not multi of 5
    [
#     Prepare else condition at CE
      >>-
#     Goto CD
      <
    ]
#   Goto CD or CE
    >+
#   Else If is multi of 5
    [    
#     Goto C10 and print Buzz
      >>>.>>>.<..
#     Goto CC (If is not multi of 5) and restore
      <<<<<<+++++
#     Goto CD, decrease, goto CE
      >->
    ]
#   Goto C2: singles, and increment
    <<<<<<<<<<<<+
#   Print C3: LF
    >.
#   Decrement C4: singles counter
    >-
  ]
# Restore C2: singles ascii 
  <<----------
# Increment C1: tens ascii
  <+
# Goto C5 (tens counter) and decrement it 
  >>>>-
]   
# Goto C10 and print Buzz
>>>>>>>>>>>.>>>.<..
\$\endgroup\$
0
8
\$\begingroup\$

Bash, 85 81 78 74 72 71 bytes

for((;i++<100;j=i%3&2|i%5/4)){
o=($i Buzz Fizz FizzBuzz)
echo ${o[j]}
}

Thanks to @Neil for saving 4 bytes!
Thanks to @manatwork for saving 3 bytes!
Thanks to @primo for saving 2 bytes!

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ for i in {1..100}\n{for((;100>i++;)){ \$\endgroup\$
    – primo
    Nov 21, 2018 at 14:59
8
\$\begingroup\$

HTML & CSS, 502 485 bytes

body{counter-reset:n}
p::after{counter-increment:n;content:counter(n)}
p:nth-child(3n)::before{content:"Fizz"}
p:nth-child(3n)::after{content:""}
p:nth-child(5n)::after{content:"Buzz"}
<p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p><p>

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Nice answer! You don't need the <div> elements and you can skip the closing </p> tags as well, it should still render fine. \$\endgroup\$
    – emanresu A
    Nov 22, 2021 at 2:53
  • \$\begingroup\$ Thanks @emanresuA. I still needed an element to apply the counter-reset to but it could just have been the body. Removing the closing </p> helped shave off a lots of bytes. \$\endgroup\$ Nov 22, 2021 at 9:02
7
\$\begingroup\$

MoonScript, 83 82 bytes

[print(i%15==0and"FizzBuzz"or(i%3==0and"Fizz")or(i%5==0and"Buzz")or i) for i=1,100]
\$\endgroup\$
1
  • 6
    \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! \$\endgroup\$
    – Dennis
    Sep 26, 2015 at 5:27
7
\$\begingroup\$

C++, 130 126 119 115

#include<iostream>
int i;int main(){for(auto&o=std::cout;++i<101;o<<'\n')i%3?o:o<<"Fizz",i%5?i%3?o<<i:o:o<<"Buzz";}

Live version.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Suggest i%3||o<<"Fizz" \$\endgroup\$
    – c--
    Jun 6, 2022 at 22:48
7
\$\begingroup\$

Brainfuck, 16321 3602 1597

Almost as short as Java. This is just the trivial answer generated by another program, This is still a computer generated answer, but I am sure there are way shorter solutions! The general idea is initializing the cells to 4 B F i u z. If the program has to output a number, it just goes to the first cell and manipualtes it, if it is one of the letters, it will just jump to the corresponding cell and output it.

++++++++++<<+++++++[>+++++++<-]>[>>+>+>+>++>++>++<<<<<<<-]>>+++>+++++++++++++++++>+++++++++++++++++++++>+++++++>+++++++++++++++++++>++++++++++++++++++++++++<<<<<---.<.>+.<.>>>.>.>>..<<<<<<.>++.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>+++.<.>+.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.>-------..<.>>>.>.>>..<<<<<<.>.++.<.>--.+++.<.>>>.>.>>..<<<<.>>>.>..<<<<<<.>---.+++++.<.>-----.++++++.<.>>>.>.>>..<<<<<<.>------.++++++++.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>-------..<.>.+.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.>-.++++.<.>>>.>.>>..<<<<<<.>----.++++++.<.>------.+++++++.<.>>>.>.>>..<<<<.>>>.>..<<<<<<.>------.--.<.>++.-.<.>>>.>.>>..<<<<<<.>+.+.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>-.++++.<.>----.+++++.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.>----.---.<.>>>.>.>>..<<<<<<.>+++.-.<.>+..<.>>>.>.>>..<<<<.>>>.>..<<<<<<.>.++.<.>--.+++.<.>>>.>.>>..<<<<<<.>---.+++++.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>----.---.<.>+++.--.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.>++.+.<.>>>.>.>>..<<<<<<.>-.+++.<.>---.++++.<.>>>.>.>>..<<<<.>>>.>..<<<<<<.>---.-----.<.>+++++.----.<.>>>.>.>>..<<<<<<.>++++.--.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>++.+.<.>-.++.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.>-.------.<.>>>.>.>>..<<<<<<.>++++++.----.<.>++++.---.<.>>>.>.>>..<<<<.>>>.>..<<<<<<.>+++.-.<.>+..<.>>>.>.>>..<<<<<<.>.++.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>-.------.<.>++++++.-----.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.>+++++.--.<.>>>.>.>>..<<<<<<.>++..<.>.+.<.>>>.>.>>..<<<<.>>>.>..<<<<<<.>.--------.<.>++++++++.-------.<.>>>.>.>>..<<<<<<.>+++++++.-----.<.>>.>>>.>..<<<<<<.>>>.>.>>..<<<<<<.>+++++.--.<.>++.-.<.>>>.>.>>..<<<<<<.>>.>>>.>..<<<<<<.
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Nice solution! I could get to 425 bytes by manually writing the brainfuck code. \$\endgroup\$ Dec 27, 2016 at 13:04
7
\$\begingroup\$

Mathematica, 83 75 73 67 62 bytes

Print/@(#/.(##&[15#->FizzBuzz,3#->Fizz,5#->Buzz]&)/@#&@Range@100)

I do not think that this could be golfed any further. Thanks to branislav for helping me golf this.

\$\endgroup\$
11
  • \$\begingroup\$ golf it down to 66 bytes by first removing all quotation marks, second using ...\\Column instead of Print/@(...) \$\endgroup\$
    – sanchez
    Oct 30, 2015 at 16:39
  • \$\begingroup\$ then how about Print/@% \$\endgroup\$
    – sanchez
    Nov 2, 2015 at 5:30
  • \$\begingroup\$ @branislav It doesn't end up saving any bytes. \$\endgroup\$ Nov 2, 2015 at 11:24
  • 6
    \$\begingroup\$ You mean Mathematica doesn't have a FizzBuzz builtin? \$\endgroup\$
    – user45941
    Nov 15, 2015 at 5:02
  • 1
    \$\begingroup\$ I should make it clear that I don't think that not working in the up-to-date version in any way invalidates this answer! But I'm interested to know what the best solution is in 11. \$\endgroup\$
    – A Simmons
    Jan 20, 2017 at 17:10
7
\$\begingroup\$

Rotor, 32 31 bytes

1N2{3%!"Fizz"~5%!"Buzz"N$?~N}\

This has one unprintable, so here's a hexdump:

0000000: 314e 7f32 7b33 2521 2246 697a 7a22 7e35  1N.2{3%!"Fizz"~5
0000010: 2521 2242 757a 7a22 4e24 3f7e 4e7d 5c    %!"Buzz"N$?~N}\

Explanation:

1  Push a one to the stack.
N  Push a newline.
^? Spooky invisible unprintable that pushes 100 to the stack.
2  Pushes a two to the stack. 
{  Starts block.
  3%      Takes mod 3 of the top number on the stack.
  !"Fizz" If falsy, push "Fizz".
  ~       Push the contents of the register.
  5%      Takes mod 5.
  !"Buzz" If falsy, push "Buzz".
  N$      Compares the top value of the stack to a newline. (this doesn't pop the values off the stack)
  ?~      If truthy, push the contents of the register.
  N       Push a newline.
}\ For loop between 2 and 100, pushing the counter to the register and stack each time.

Try it online. (note that it is very slow)

Check out Rotor.

\$\endgroup\$
7
\$\begingroup\$

05AB1E, 29 bytes

тLʒ"Fizz"D'ÒÖ™DŠ«)¬ÑD5ås3å«è,

Try it online!

To my surprise (or my incapability to use the search function) there was no 05AB1E answer to this question.

Explanation

тLʒ"Fizz"D'ÒÖ™DŠ«)¬ÑD5ås3å«è,
тL                            # push [1,...,100]
  ʒ                           # for each...
   "Fizz"                      # Push Fizz (didn't find a way to shorten this one sadly)
         D                     # Duplicate
          'ÒÖ™                 # Push Buzz
              D                # Duplicate
               Š               # Move top item on the stack two slots down
                «              # Concatenate the top items (Results in FizzBuzz)
                 )             # Wrap stack to array
                  „           # Get Divisors of N
                    D5å        # Does 5 divide it?
                       s3å     # Does 3 divide it?
                          «    # Concatenate top two items
                           è,  # Gets item in the array at the index of the concatenated divisors (indexing wraps around) and prints  
                   
\$\endgroup\$
7
\$\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.

\$\endgroup\$
7
\$\begingroup\$

Common Lisp, 103 101 96 93 84 bytes

(dotimes(i 101)(format t"~v^~[Fizz~[Buzz~]~:;~[Buzz~:;~a~]~]
"i(mod i 3)(mod i 5)i))

Try it online!

It's shorter than other CL solution and it uses different method. Conditions are handled inside format function.

-5 bytes - shorter version of handling i=0

-3 bytes - ~^ with only one parameter seems to work as if second parameter was 0, which is saves 2 bytes. Last byte is saved by substituting ~% by <enter>

-9 bytes - by ASCII-only

\$\endgroup\$
3
  • \$\begingroup\$ You can use ~[ instead of ~:[ and remove the (= ... 0) to reduce it to 84 bytes (with a bit of rearrangement). (not posting link because it would spoiler current code-golf.io best) \$\endgroup\$
    – ASCII-only
    May 16, 2018 at 9:26
  • \$\begingroup\$ @ASCII-only Thank you for suggestion but it seems unobvious, how to do it. Without (=(mod i 5)0) I seem to need to handle residues of 1,2,3,4 separately (and similiarily for (=(mod i 3)0): 1 and 2). \$\endgroup\$
    – user65167
    May 24, 2018 at 20:08
  • 1
    \$\begingroup\$ No... just use ~:; to add a default fallback: (dotimes(i 101)(format t"~v^~[Fizz~[Buzz~]~:;~[Buzz~:;~a~]~]<newline>"i(mod i 3)(mod i 5)i)) where <newline> is replaced with literal newline \$\endgroup\$
    – ASCII-only
    May 24, 2018 at 23:33
7
\$\begingroup\$

BuzzFizz, 86 bytes

$a++
if3\$a:print"Fizz"
if5\$a:print"Buzz"
else:print$a
print"\n"
if100\$a:#
else:loop

Try it online!

Explanation

Despite being golfed, all you have to do is to add a bit of horizontal whitespace and a few comments to get possibly one of the clearest and most readable FizzBuzzes ever. (Vertical whitespace is significant in BuzzFizz, apart from (by popular demand) the trailing newline, so it's necessary even in a golfed program.)

# Counters start at 0. So $a will be increased to 1 on the first iteration.
# On subsequent iterations, it counts up by 1 each time.
$a++

# BuzzFizz supports only one operator: \, the "divides into" relational
# operator. So you'll be seeing that every time there's an if statement.
# It's pretty helpful for a fizzbuzz!
if 3\$a: print "Fizz"
if 5\$a: print "Buzz"

# The "else" statement attaches to *both* "if" statements simultaneously;
# it'll only run if neither of them did. "else" always attaches to all
# "if" statements since the preceding "else", so sometimes a dummy "else"
# statement is needed in order to clear the state. We don't need to
# resort to that for our FizzBuzz program, though.
else: print $a

# Now we've printed Fizz/Buzz/FizzBuzz/the number, print a newline.
print "\n"

# Our loop ends when $a becomes 100. 100 is the lowest positive integer
# that's divisible by 100, so we can use a divisibility test to find
# the end of the loop. We negate the test via the use of a comment as
# the body of the "if" statement (an "if" body cannot be empty in
# BuzzFizz, but a comment counts as a statement).
if 100\$a: # do nothing

# If $a is *not* divisible by 100, we have another iteration. So loop
# back to the start of the program.
else: loop

Discussion

In addition to the commands seen in the FizzBuzz program above, BuzzFizz also supports input (if you use an identifier like a with no leading $, the program will ask for its value; you can use a statement like clear a to reset the value so that the program asks for it again the next time it's used). Other than that, the above program shows off all the features of the language; in other words, we have a complete language built entirely out of the operations you need to write a simple FizzBuzz program (thus the name).

Despite its inspiration, BuzzFizz is not specialised merely for FizzBuzzes; you can take the FizzBuzz program apart, put it together in other ways, and solve a surprisingly large range of problems. For example, the Esolang page for the language has a primality tester and a program which adds two positive numbers. (The primality tester is simpler than the addition program; given BuzzFizz's choice of operator, this probably shouldn't be too surprising.)

That said, the language is (intentionally) not Turing-complete; the original inspiration of the language was to act as a counterexample to people who made claims of the form "any language that can do X must be Turing-complete", as the most common choices of X don't actually require it. On the other hand, it's also (intentionally) very powerful for a sub-Turing language; it's fairly hard to come up with simple problems that BuzzFizz can't solve and Turing-complete languages can.

\$\endgroup\$
7
\$\begingroup\$

J, 45 bytes

New Version, thanks to Bolce Bussiere:

(,&((;,>)Fizz`Buzz)@":{~+.&3-~0:<5&|)"0>:i.100

Old version (52 bytes):

(,&('Fizz'(,>@;;)'Buzz')@":{~+.&3-~0:~:5&|)"0>:i.100

Explanation

Best explained by breaking it up into smaller verbs. Overall the main working portion is a train:

getlist {~ getindex

where getlist i returns a 4-length list of the default format of i, 'FizzBuzz', 'Fizz', and 'Buzz'; and getindex i returns -1 if i is divisible by 5 only, -2 if divisible by 3 only, 1 if divisible by both, and 0 otherwise. The verb {~ grabs the right argumentth element from its left argument, the list created by getlist, where the index is modulo'd by the length of the list, meaning -1 will grab the last element, -2 the second-to-last, etc.

In

getlist=:,&('Fizz'(,>@;;)'Buzz')@":

": gets the default format of i, and then ,&('Fizz'(,>@;;)'Buzz') appends it to the beginning of the list created using the train ,>@;; on the two arguments 'Fizz' and 'Buzz' (append them and raze them, then raze those results together and unbox each item), in the new version ((;,>)Fizz`Buzz) does essentially the same thing but takes advantage of the ` that boxes, then appends the two strings before applying the train ;,> on the resulting list of boxes (unbox each element; raze the elements together to get FizzBuzz; append the unboxed elements with FizzBuzz)

In

getindex=:+.&3-~0:~:5&|

+.&3 gets the GCD of i and 3, and 5&| returns i modulo 5. The train 0:~:5&| returns 1 if 5&| is unequal (~:, or in the new version < because the result of 5&| will always be greater than or equal to 0) to the result of the constant function 0: (which returns 0 for any argument) and 0 otherwise, then getindex is a train that, from this value, subtracts +.&3 resulting in the return values given above.

The boring parts are the "0 which simply tells the verb to operate on atoms of any argument given to it, and >:i.100, which returns a list of integers from 1 to 100 (inclusive).

\$\endgroup\$
6
  • \$\begingroup\$ Using < instead of ~: saves a byte \$\endgroup\$ Apr 6, 2019 at 16:42
  • 1
    \$\begingroup\$ And (;,>)Fizz`Buzz instead of 'Fizz'(,>@;;)'Buzz' saves another 5 \$\endgroup\$ Apr 6, 2019 at 16:56
  • 1
    \$\begingroup\$ @BolceBussiere < instead of :~:? \$\endgroup\$
    – ASCII-only
    Apr 8, 2019 at 4:17
  • \$\begingroup\$ @ASCII-only the first : belongs to the verb 0: that returns the constant 0. The verb ~: represents 'not equal' \$\endgroup\$ Apr 9, 2019 at 17:29
  • \$\begingroup\$ Idk, using just constant 0 worked for me \$\endgroup\$
    – ASCII-only
    Apr 9, 2019 at 23:02
1
2
3 4 5
14

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.