200
\$\begingroup\$

Introduction

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

Challenge

Write a program that prints the decimal numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Output

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

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

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

Further Rules

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

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

  • Nothing can be printed to STDERR.

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

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

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

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

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

  • Standard loopholes are otherwise disallowed.

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

Catalogue

var QUESTION_ID=58615;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=30525;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table>

\$\endgroup\$
14
  • 1
    \$\begingroup\$ Nothing can be printed to STDERR. Is this true only when running, or also when compiling (assuming that is a separate step?) \$\endgroup\$
    – AShelly
    Commented Sep 24, 2015 at 20:47
  • 1
    \$\begingroup\$ @AShelly Only when running \$\endgroup\$
    – Beta Decay
    Commented Sep 24, 2015 at 20:48
  • 1
    \$\begingroup\$ I’m not sure I like the fact that you hardcoded the 100 into the challenge. That way, a program that just generates the expected output is a valid entry, but is not interesting for this challenge. I think the challenge should expect the program to input the number of items to output. \$\endgroup\$
    – Timwi
    Commented Sep 24, 2015 at 23:28
  • 9
    \$\begingroup\$ @Timwi While I agree that it would make it (only slightly) more interesting, I've very often seen FizzBuzz as strictly 1 to 100 (on Wikipedia and Rosetta Code, for example). If the goal is to have a "canonical" FB challenge, it makes sense. \$\endgroup\$
    – Geobits
    Commented Sep 25, 2015 at 0:50
  • 77
    \$\begingroup\$ A "vanilla fizzbuzz" sounds delicious. \$\endgroup\$ Commented Sep 25, 2015 at 15:12

426 Answers 426

1
8 9
10
11 12
15
2
\$\begingroup\$

Terse, 22 bytes

电让一3我5u"Fizz‘Buzz"死开】而

Try it here

A golfing language made by me.

\$\endgroup\$
2
\$\begingroup\$

Python, 580 bytes

Here's a version that pre-computes the FizzBuzz table and then just returns a slice, which would be useful if you're running a worldwide FizzBuzz service. It'd be more interesting in a language that has slices as a first-class construct. Either way, a very unoptimized implementation:

from typing import List

class FizzBuzz:
    def __init__(self, max_n=10**4):
        self.max_n = max_n
        self.data = [i for i in range(0, self.max_n)]
        for r in range(0, self.max_n, 3):
            self.data[r] = "Fizz"
        for r in range(0, self.max_n, 5):
            self.data[r] = "Buzz"
        for r in range(0, self.max_n, 15):
            self.data[r] = "FizzBuzz"

    def fizzBuzz(self, n: int) -> List[str]:
        if n > self.max_n or n < 1:
            return None  # Out of range, not permitted
        return self.data[1:n]

s = FizzBuzz()
print(s.fizzBuzz(100))
```
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! This site is for competitive challenges, not general programming questions.This challenge has minimum code size as its goal, and isn't just asking for answerers to create a FizzBuzz program (however interesting it is) unless some effort has been made to optimize its size. \$\endgroup\$
    – rydwolf
    Commented Dec 4, 2022 at 2:51
2
\$\begingroup\$

Functional(), 314 310 288 277 273 269 bytes

0,1,=,:,$,&,$(X,& >($(I,T(>(a,b,c,d),b d(0,I)(= a,a(=,1)b,a b(=,1)c,a b(c,d))))1))(:(T,&(a,b,c,d))(X(T(b(d,a c)($(S,T(W()1 b()0()1()1 0(= b)b(= b)>()0 1()> >()0 1()> > 0,0)),=(:(t,t(S,1)))(0,&()(u()>()0,:(W,T(>(a 1),W))a b c d >()0)))0,W()1()1()0()0)),:(u,&()(W a b c d

Try it online!
Try the 273B version online!
Try the 277B version online!
Try the 288B version online!
Try the 310B version online!
Try the 314B version online!

in a more readable form ( ommited last )s are added ):

0,1,=,:,$,&,
$(X,& >(
  $(I,T(
    >(a,b,c,d),
    b d (0,I)(= a,a(=,1)b,a b(=,1)c,a b(c,d))
  )) 1
))(
 :(T,&(a,b,c,d))(
  X(
   T(
    b(d,a c)(
     $(S,T(
       W() 1 b () 0 () 1 () 1 0 (= b) b (= b) > () 0 1 () > > () 0 1 () > > 0,
       0
     )),
     =(
      :(t,t(S,1))
     )(
      0,
      &()(
       u() > () 0,
       :(W,T(>(a 1),W)) a b c d > () 0
      )
     )
    ) 0,
    W() 1 () 1 () 0 () 0
   )
  ),
  :(u,&()(W a b c d))
 )
)

explanation

The key of this code is a executer func "X" like a pseudo Python code below;

def executer(f):
  def incrementer(a,b=0,c=0,d=0):
    f(a,b,c,d)
    nextf = nullf if b==1 and d==1 else incrementer
    # nullf is a function to do nothing
    nextf(1^a,a^b,(a&b)^c,(a&b&c)|d)

  incrementer(1)

Then, this realize a 10-length loop to evaluate f(1,0,0,0), f(0,1,0,0), f(1,1,0,0), ... , f(0,1,0,1) in this order. The parameters a,b,c,d describe 4 bits of 1 thru 10 ( the lowest bit first ).

Thus, the rough structure of this code is a double loop with "X" like below;

X(
 T(
  X(
   T(
    ** main part
    * print Fizz or Buzz or FizzBuzz or the sequence number
    * and print a newline
   )
  ),
  ** post process
  * re-assign "u", a func to print the upper digit, for the next iteration
 )
)

"T" is a "function template" and acts like a synonym of "&(a,b,c,d)" ( a user function template with 4 parameters a,b,c,d ) due to the assignment with ":" at the 8th line.

In addition to "X" and "T", I implemented "W" and "S" func for output.
"W" is for bit-sequence output. "W" returns "W" itself after printing bits so that "W 0 1 0 1 0 0 0 0" print a bit sequence ( a newline in this case ) continuously for example. And "W" takes a parameter as a bit to print, but is improved, for compressing bit streams, to print two bits of 11 at a time with ">" .
"S" is for "Fizz" ( against parameter (x,1) ) or "Buzz" ( against parameters (x,0) ) output with "W".

Other function "u" and "t" are variable over the double loop.
"u" is for printing the lower 4 bits of the upper digits, and is re-assigned in the post process of the outer loop.
"t" acts as a 3 state register, which holds 0, 1 and "S", and is re-assigned with ":(t,t(S,1))" on every loop iteration. When "t" is 0 or 1, it is re-assigned with 1 or "S" respectively. And when "t" is "S", it is re-assigned with 0 as a return value of "S" after printing "Fizz".

\$\endgroup\$
2
\$\begingroup\$

Miled, 143127 bytes

I don't know if a language in alpha is allowed, but here it is.

-16 by myself. Yes. I was dumb.

join "\n" map fn cS "x" <: if:: div 15 x "FizzBuzz" else if:: div 3 x "Fizz" else if:: div 5 x "Buzz" else ->str x :> ..= 1 100

TIO (read: Try It Offline)

A little note on this language: it's created by me. The current release is the first release of the language and it's still in alpha, so expect bugs. I haven't encountered any yet, so I think, maybe the best way to test it is to make more people use it! So if you find bugs, please report it. And I'm just a hobbyist with few coding experiences, so please give me advices. Thanks!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ languages in alpha/heavy development are definitely allowed - the implementation defines the language, so the language here is Miled (alpha) (or whatever versioning system you choose). I submitted a fizzbuzz for a in-dev alpha esolang once and no one was upset that it was still in development, so people won't be upset with this answer too. You can also always update this answer as later versions of Miled are released. Anyhow, this esolang looks really cool and I look forward to seeing how it turns out! :) \$\endgroup\$
    – lyxal
    Commented Dec 13, 2022 at 11:40
2
\$\begingroup\$

Thunno N, \$35\log_{256}(95)\$ ≈ 28.80921 bytes

aSR1+eD3 5ZP%0="FizzBuzz"2APz*JD!?K

Attempt This Online! (not yet though)

Thought I'd try my usual approach in Thunno to see how it turned out.

Explained

aSR1+eD3 5ZP%0="FizzBuzz"2APz*JD!?K
aSR1+                               # The range [1, 100]
     e                              # To each item:
      D                             #   Duplicate it
       3 5ZP%                       #   [% 3, % 5]
             0=                     #   == 0
               "FizzBuzz"2AP        #   ["Fizz", "Buzz"]
                            z*      #   repeated element-wise
                              J     #   "".join
                               D!?K #   if that's empty, leave the original number
# The N flag, of course, joins the output on newlines
\$\endgroup\$
0
2
\$\begingroup\$

jq -nr, 43 bytes

Exploiting that out-of-bounds array access evaluates to null. Works with jq 1.5+

range(100)+1|["Fizz"][.%3]+["Buzz"][.%5]//.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Desmos, 244 bytes

a=\left[1...100\right]
b\left(m\right)=\operatorname{mod}\left(a,m\right)
c\left(n\right)=\left\{b\left(n\right)=0:1,0\right\}
\left(a,1\right)Fizzc\left(3\right)
\left(a,0\right)Buzzc\left(5\right)
\left(a,0\right)${a}b\left(3\right)b\left(5\right)

Ungolfed

  • a=\left[1...100\right] sets a to be [1,2,3,4...100]
  • b\left(m\right)=\operatorname{mod}\left(a,m\right) b(m)=mod(a,m)
  • c\left(n\right)=\left\{b\left(n\right)=0:1,0\right\}if b(n)=0,output 1,otherwise 0
  • \left(a,1\right)Fizzc\left(3\right)This is just points at (a,1) labeled with fizz, and opacity c(3)
  • \left(a,0\right)Buzzc\left(5\right) Same with Buzz
  • \left(a,0\right)${a}b\left(3\right)b\left(5\right) Points at (a,0) with label a, opacity b(3)b(5)
\$\endgroup\$
2
\$\begingroup\$

SAS 4GL, 84 (or 81 or 72 or 63) 100 (or 89? ) 110 bytes (or 104? or 88?) 133 bytes (or 120? or 111?) 142 bytes (or 129? or 120?) (out of game 82)

  1. The code (short)
data;do n=1to 1e2;x=scan('Fizz FizzBuzz Buzz'!!n,mod(gcd(n,15),11)-2);put x;end;run;

  1. The "human readable" code
data;
  do n = 1 to 1e2;
    x = scan('Fizz FizzBuzz Buzz'!!n, mod(gcd(n, 15), 11) - 2);
    put x;
  end;
run;

Explanation (for n=20):

data;
  do n = 1 to 20;
    g = gcd(n, 15);
    m = mod(g, 11) - 2;
    y = 'Fizz FizzBuzz Buzz' !! n;
    x = scan(y, m);
    put n= @10 g= @20 m= @30 y= @70 x=;
  end;
run;

Variables:

  • g from greatest common divisor function gets : 1,3,5,15,
  • m from modulo function gets: -1,1,3,2,
  • y gets: "Fizz FizzBuzz Buzz          n" for n,
  • x value is scanned from y on position m (negative m means "scan backward").

SAS Log printout:

n=1      g=1       m=-1      y=Fizz FizzBuzz Buzz           1        x=1
n=2      g=1       m=-1      y=Fizz FizzBuzz Buzz           2        x=2
n=3      g=3       m=1       y=Fizz FizzBuzz Buzz           3        x=Fizz
n=4      g=1       m=-1      y=Fizz FizzBuzz Buzz           4        x=4
n=5      g=5       m=3       y=Fizz FizzBuzz Buzz           5        x=Buzz
n=6      g=3       m=1       y=Fizz FizzBuzz Buzz           6        x=Fizz
n=7      g=1       m=-1      y=Fizz FizzBuzz Buzz           7        x=7
n=8      g=1       m=-1      y=Fizz FizzBuzz Buzz           8        x=8
n=9      g=3       m=1       y=Fizz FizzBuzz Buzz           9        x=Fizz
n=10     g=5       m=3       y=Fizz FizzBuzz Buzz          10        x=Buzz
n=11     g=1       m=-1      y=Fizz FizzBuzz Buzz          11        x=11
n=12     g=3       m=1       y=Fizz FizzBuzz Buzz          12        x=Fizz
n=13     g=1       m=-1      y=Fizz FizzBuzz Buzz          13        x=13
n=14     g=1       m=-1      y=Fizz FizzBuzz Buzz          14        x=14
n=15     g=15      m=2       y=Fizz FizzBuzz Buzz          15        x=FizzBuzz
n=16     g=1       m=-1      y=Fizz FizzBuzz Buzz          16        x=16
n=17     g=1       m=-1      y=Fizz FizzBuzz Buzz          17        x=17
n=18     g=3       m=1       y=Fizz FizzBuzz Buzz          18        x=Fizz
n=19     g=1       m=-1      y=Fizz FizzBuzz Buzz          19        x=19
n=20     g=5       m=3       y=Fizz FizzBuzz Buzz          20        x=Buzz

Remarks:

  • if you decide to uses F, B, and FB for Fizz, Buzz, and FizzBuzz it can be shortened to:
data;do n=1to 1e2;x=scan('F FB B'!!n,mod(gcd(n,15),11)-2);put x;end;run;

so 72, right? ;-)

  • The data; and run; are mandatory keywords of every SAS 4GL data step, so if you thinking only about the "working code" (and have in mind the previous remark) you could say 63 bytes, right? ;-) ;-)

Observation

I dare to say that "FizzBuzz" is equivalent with "BuzzFizz", after all if a number is divisible by "3 and 5" it is also divisible by "5 and 3", isn't it? In such case it can be golfed to 81 bytes:

data;
  do n = 1 to 1e2;
    t='Fizz Buzz';
    x = scan(t!!t!!n, mod(gcd(n, 15), 11) - 2);
    put x;
  end;
run;

Until I get confirmation I'll keep it unofficial.



The 4th obsolete solution.

  1. The code (short)
data;do n=1to 1e2;f=^mod(n,3);b=^mod(n,5);put n@(4*^(f+b))"Fizz"+(-4*^f)"Buzz"+(-4*^b)4*" ";end;run;

  1. The "human readable" code

The Code:

data;
  do n=1to 1e2;

    f=^mod(n,3);
    b=^mod(n,5);

    put n@(4*^(f+b))"Fizz"+(-4*^f)"Buzz"+(-4*^b)4*" ";

  end;
run;

Process:

  • print n and overprint it with Fizz, Buzz or FizzBuzz if divisibility occurs by shifting text with @() operator.

Remarks:

  • if you decide to uses F, B for Fizz and Buzz it can be shortened to:
data;do n=1to 1e2;f=^mod(n,3);b=^mod(n,5);put n@(4*^(f+b))"F"+(-^f)"B"+(-^b)"  ";end;run;

so 89, right? ;-) ;-)


"Out-of-game 82"

This example "breaks" the rule because it uses F, B and X instead full words, that is why I only puts it as a interesting case. It is a variation on the cycle string idea. And I like it the most :-)

The code:

data;do n=1 to 100;x=coalescec(char("X  F BF  BF B",mod(n,15)+1),n);put x;end;run;

Human readable:

data;
  do n = 1 to 100;
    x = coalescec(char("X  F BF  BF B", mod(n, 15) + 1), n);
    put x;
  end;
run;

If you will to create a SAS format:

proc format;
 value $ X (default=20)
 "F" = "Fizz"
 "B" = "Buzz"
 "X" = "FizzBuzz"
 ;
run;

and modify the put statement to:

put x $X.;

you will see "full words" in the log.



The 3rd obsolete solution.

  1. The code (short)
data;do n=1to 100;x=ifc(mod(n,5)*mod(n,3),n,ifc(^mod(n,5),"Fizz","")!!ifc(^mod(n,3),"Buzz",""));put x;end;run;

  1. The "human readable" code

The Code:

data;
  do n = 1 to 100;
    x =                       /* create variable x and... */
        ifc(mod(n,5)*mod(n,3) /* if n not divisible by 3 or 5 */
            ,n                /* assign n to x, else... */
            ,ifc(^mod(n,5)    /* if divisible by 5 add Fizz string to x */
                 ,"Fizz"
                 ,"")
             !!               /* and concatenate with... */
             ifc(^mod(n,3)    /* if divisible by 5 add Buzz string */
                 ,"Buzz"
                 ,"")
             );
    put x ;                   /* print value from x variable */
  end;
run;

Comments:

  • It looks like "concatenation" of four mod(.,.) functions and three ifc() functions do the job even better.

Remarks:

  • If the Fizz and Buzz phrases could be "replaced" by F and B the code would be 6 bytes shorter, that's why I wrote 104 in brackets. :-)
  • The data; and run; are mandatory keywords of every SAS 4GL data step, so if you thinking only about the "working code" (and have in mind the previous remark) you could say 95 bytes, right? ;-) ;-)


The 2nd obsolete solution.

  1. The code (short)
data;do n=1to 100;select;when(^mod(n,15))put"FizzBuzz";when(^mod(n,5))put"Fizz";when(^mod(n,3))put"Buzz";otherwise put n;end;end;run;

  1. The "human readable" code

The Code:

data;
  do n = 1 to 100;
    x = ifc(mod(n,5)*mod(n,3)
            ,n
            ,ifc(^mod(n,5)
                 ,"Fizz"
                 ,"")
             !!
             ifc(^mod(n,3)
                 ,"Buzz"
                 ,"")
             );
    put x ;
  end;
run;

Comments:

  • It looks like doing 3 times "negated modulo" (^mod(.,.)) takes less keystrokes than previous "cycle string" approach.

  • Remarks from the previous one stay, but with 120 and 111 accordingly. ;-) ;-)



The 1st obsolete solution.

  1. The code (short)
data;do n=1to 100;select(char("300102100120100",mod(n,15)+1));when(0)put n;when(1)put"Fizz";when(2)put"Buzz";when(3)put"FizzBuzz";end;end;run;

  1. The "human readable" code "step by step"

The Code:

data;
  do n = 1 to 100;

    select( char( "300102100120100", mod(n, 15) + 1) );
      when(0) put n;
      when(1) put "Fizz";
      when(2) put "Buzz";
      when(3) put "FizzBuzz";
    end;

  end;
run;

The process:

  • the do n = 1 to 100; makes the loop from 1 to 100, so if you want to play FizzBuzz for 1000 it is just 1 extra byte cost,
  • "300102100120100" - the "cycle string" - when you realise the divisibility by 3 or 5 is cyclic modulo 15 you will see all "cases" repeating in a loop; you just have to put the last marker (3 = divisible by 3 and 5) as the first on the list (since 15 modulo 15 is 0).
  • char( "300102100120100", mod(n, 15) + 1) select "n-th modulo 15, plus 1" character from the "cycle string", do the test in when(), and print with put.

Remarks:

  • If the Fizz, Buzz, and FizzBuzz phrases could be "replaced" by F, B, and X the code would be 13 bytes shorter, that's why I wrote 129 in brackets. :-)
  • The data; and run; are mandatory keywords of every SAS 4GL data step, so if you thinking only about the "working code" (and have in mind the previous remark) you could say 120 bytes, right? ;-) ;-)
\$\endgroup\$
2
\$\begingroup\$

Janet, 106 bytes

Note: Janet is not in TIO so I couldn't put a link or anything.

(loop[i :range[1 101]:let[f(zero?(% i 3))b(zero?(% i 5))]](print(cond(and f b)"FizzBuzz"f"Fizz"b"Buzz"i)))
\$\endgroup\$
4
  • \$\begingroup\$ Replace (zero? ...) with (= ... 0) to shave a few bytes. \$\endgroup\$ Commented Oct 7, 2023 at 0:15
  • \$\begingroup\$ Uhm... I tried that, but it didn't work. Lemme try it again, I didn't do it exactly the same way ur trying. \$\endgroup\$ Commented Oct 7, 2023 at 2:59
  • \$\begingroup\$ I tested my version on the online REPL at Janet for Mortals (I have never used Janet before but have used similar languages) \$\endgroup\$ Commented Oct 7, 2023 at 3:01
  • \$\begingroup\$ I will try tomorrow gtg now. I will comment by noon pst if it works. But thanks! \$\endgroup\$ Commented Oct 7, 2023 at 3:05
2
\$\begingroup\$

Easyfuck, 103 92 90 bytes

Æ¡ãÄ©␟[Vîê§VTSx(\ùòîO␗.SÉD§ÏAPC>|¥ãÄSTSHYÞHù␋åoPU2c[HOPD®␊y$|NELóçÉ␞c[HOPD§Ü␔ò|úÛÇHTJÝÝCCHñsÄSTMWÞ»␂4-=}d␂␄␘\¢PAD

due to lack of unicode representations for c1 control characters, they have been replaced by their superscripted abbreviations

Decompressed:

c(<<%$>[+;]*<)p(.>>.r<..)r(J>>>>>)<<$r[^$>!>+>$c-`(Jp)r$>!>>>$<c-`(J>p)r>>[<<';]J<.<$r+^]@FBiuzd␁␁␃␅e␊

Explanation part 1:

c(<<%$>[+;]*<)p(.>>.r<..)r(J>>>>>)<<$r
c(           )                         define function c
  <<                                   go to the cell 2 steps to the left
    %$>                                modulo the cell by the value in storage, copy it to storage, move 1 cell to the right
       [  ]                            while loop
        +; *<                          increment the cell, break out of the while, multiply it by the value in storage, and move 1 cell to the left
              p(        )              define function p
                .>>.r<..               print ascii, move 2 cells to the right, print ascii, invoke function r, move 1 cell to the left, print ascii twice
                         r(      )     define function r
                           J>>>>>      go to the first cell and move 5 cells to the right
                                  <<$r move to the 2nd to last cell, copy it to storage and invoke function r

Explanation part 2:

[^$>!>+>$c-`(Jp)r$>!>>>$<c-`(J>p)r>>[<<';]J<.<$r+^]@FBiuzd␁␁␃␅e␊
[                                                 ]              while loop
 ^                                                               bitwise xor the cell with the storage cell
  $>!>+>                                                         copy the cell to storage, move 1 cell right, set the cell to value in storage, move 1 cell right, increment, move 1 cell right
        $c-                                                      copy the cell to storage, invoke function c, decrement
           `(Jp)                                                 if previous command caused an overflow, execute a lambda which moves the pointer to the first cell and invokes function p
                r$>!>>>                                          invoke function r, copy the cell to storage, move 1 cell to the right, set the cell to value in storage, then move 3 cells right
                       $<c-                                      copy the cell to storage, move 1 cell left, invoke function c, decrement
                           `(J>p)                                if previous command caused an overflow, execute a lambda which moves the pointer to the second cell and invokes function p
                                 r>>                             invoke function r and move 2 cells to the right
                                    [    ]                       while loop
                                     <<';                        move 2 cells left, print integer in the cell at the pointer, break out of the while
                                          J<.<$                  move to the last cell, print ascii, move 1 cell left, copy it to storage
                                               r+^               invoke function r, increment the cell at the pointer and xor it with storage cell
                                                   @             terminate program
                                                    FBiuzd␁␁␃␅e␊ initializer data
\$\endgroup\$
2
\$\begingroup\$

Uiua, 43 39 37 bytes

≡(&p◌⍥:±⧻.▽▽4=0◿3_5,"FizzBuzz")+1⇡100

Try it

    80          # this runs on each 1 to 100; consider the 80th run
80
    ,"FizzBuzz"
80
"FizzBuzz"
80
    =0◿3_5      # check divisibility against 3 and 5
80
"FizzBuzz"
[0 1]
    ▽4          # take 4 of each
80
"FizzBuzz"
[0 0 0 0 1 1 1 1]
    ▽           # use this as a filter on "FizzBuzz"
80
"Buzz"
    ◌⍥:±⧻.      # pick based on whether the string is empty or not
"Buzz"
    &p          # print with newline
Buzz
\$\endgroup\$
2
\$\begingroup\$

Rockstar, 138 135 133 bytes

F takes I&S
let M be N/I
turn up M
if N-I*M
S's ""

give S

N's 0
while N-100
build N up
say F taking 3,"Fizz"+F taking 5,"Buzz" or N

Try it here (Code will need to be pasted in)

F takes I&S             :Function F, taking an integer I & string S as arguments
let M be N/I            :  Assign N/I to variable M
turn up M               :  Round M up
if not N-I*M            :  If N is less than I*M
S's ""                  :    Assign the (falsey) empty string to S
                        :  End if
give S                  :  Return S
                        :End function
N's 0                   :Initialise N as 0
while N-100             :While N is less than 100
build N up              :  Increment N
say                     :Output
  F taking 3,"Fizz"     :  The return value of a call to F with arguments 3 & "Fizz"
  +                     :  Append
  F taking 5,"Buzz"     :  The return value of a call to F with arguments 5 & "Buzz"
  or N                  :  Logical OR with N
\$\endgroup\$
2
\$\begingroup\$

Scratch, 157 156 142 bytes

define(n)(o
replace item((b)-((b)mod(n)))of[q v]with(o
when gf clicked
repeat(100
change[b v]by(1
add(b)to[q v
(3)[Fizz
(5)[Buzz
(15)[FizzBuzz

Note: This requires b to have the value 0 before starting (which is the default value that all variables are initialized to upon creation in Scratch), and it requires the list q to be blank and displayed (which are the default conditions when creating a list).

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to CGSE! Nice answer! \$\endgroup\$ Commented Oct 16 at 19:40
2
\$\begingroup\$

TinyAPL, 64 bytes (SBCS)

⊃⍪¨⍆((⊃¨⍪¨⍆¨(4×0=3‿5|ᑈx)↑¨ᐵ"Fizz"‿"Buzz")↾¨'0'+10⊤ᑈx←⍳100)⍪ᐵ"⍘n"

Try it online!

After messing around with this last night, I cleaned it up a bit and decided to post it. It's still awful but it works.

                                                    x←             Assign x to
                                                      ⍳100         A range from 1 to 100
                                                10⊤ᑈ              Convert each to base 10
                                            '0'+                   Add the character '0' to each, casting to a string of digits

                     ᑈx                                            To each element of x
                    |                                              Take the remainder when dividing by
                 3‿5                                               Each of [3, 5]
             4×0=                                                  Check if these are 0 (i.e. divisible by 3/5) and multiply by 4, giving 4 for divisible, 0 for not
            (           ) ¨ᐵ                                       Over each of those pairs
                         ↑                                         Take the first n characters of 
                             "Fizz"‿"Buzz"                         Each of "Fizz" and "Buzz"
      ⊃¨⍪¨⍆¨                                                        And concatenate each into a string
     (                                    )↾¨                       Take the pairwise maximum with the stringified ints from before
    (                                                      )⍪ᐵ"⍘n"  Append a newline to each
⊃⍪¨⍆                                                                And concatenate the whole thing
\$\endgroup\$
2
  • \$\begingroup\$ for -2, you don't need brackets around 3‿5 \$\endgroup\$
    – RubenVerg
    Commented Oct 16 at 5:51
  • \$\begingroup\$ also in beta there's a SBCS: (⎕Import"std:sbcs")→Encode and (⎕Import"std:sbcs")→Decode, so you can count those instead of UTF8 \$\endgroup\$
    – RubenVerg
    Commented Oct 16 at 5:55
1
\$\begingroup\$

JavaScript, 73 bytes

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

Hassium, 160 Bytes

Here's it in Hassium. Surprised there's never been a FizzBuzz challenge before. There's also some lengthier (but more interesting) FizzBuzz examples here

func main(){foreach(x in range(1,100)){if(x%15==0){println("fizzbuzz");}else if(x%3==0){println("fizz");}else if(x%5==0){println("buzz");}else println(x);}}

Run online and see expanded version here

\$\endgroup\$
2
  • \$\begingroup\$ @FryAmTheEggman Duly noted and added. Thanks. \$\endgroup\$ Commented Sep 25, 2015 at 2:19
  • 3
    \$\begingroup\$ 1. The capitalization of Fizz and Buzz is wrong. 2. <1 is shorter than ==0. 3. All curly braces ({}) can be eliminated. \$\endgroup\$
    – Dennis
    Commented Sep 25, 2015 at 5:29
1
\$\begingroup\$

Frink, 131 bytes

This is still to be golfed, but because the docs are bare bones, it will be golfed through experimentation

for x=1 to 100
{
if x%15==0
{
println["FizzBuzz"]
} else
{
if x%3==0
{
println["Fizz"]
} else
{
if x%5==0
{
println["Buzz"]
} else 
{
println[x]
}
}
}
}
\$\endgroup\$
4
  • \$\begingroup\$ By my reading of the linked page only the for loop's braces are necessary. \$\endgroup\$
    – Neil
    Commented Sep 29, 2015 at 14:56
  • \$\begingroup\$ @Neil Then you'd need then which would increase the byte count \$\endgroup\$
    – Beta Decay
    Commented Sep 29, 2015 at 16:01
  • \$\begingroup\$ No, that's only if you want the controlled statement on the same line. \$\endgroup\$
    – Neil
    Commented Sep 29, 2015 at 16:13
  • \$\begingroup\$ I might have misread so you might still need the braces on the outer else clauses too. \$\endgroup\$
    – Neil
    Commented Sep 29, 2015 at 16:36
1
\$\begingroup\$

Groovy, 71 bytes

(1..100).each{i->println i%15<1?'FizzBuzz':i%5<1?'Buzz':i%3<1?'Fizz':i}
\$\endgroup\$
1
\$\begingroup\$

Swift, 77 bytes

for i in 1...100{print(i%15<1 ?"FizzBuzz":i%3<1 ?"Fizz":i%5<1 ?"Buzz":"\(i)")}
\$\endgroup\$
1
  • \$\begingroup\$ @RichardG.Nielsen It's considered poor etiquette to edit some else's golfed code. Suggesting it in a comment is fine, or you could post your own answer since you came up with it independently. \$\endgroup\$
    – feersum
    Commented Oct 27, 2015 at 11:43
1
\$\begingroup\$

STATA, 115 bytes

qui{
set ob 100
g a="Fizz" if!mod(_n,3)
g b="Buzz" if!mod(_n,5)
g c=a+b
replace c=string(_n) if c==""
}
l c,noo noh

qui{} suppresses output for everything in that block. First set the number of observations to be 100. Then generate variable a to be "Fizz" for every observation where its index number is divisible by 3. Then generate variable b to be "Buzz" for every observation where its index number is divisible by 5. Generate variable c to be the concatenation of these two. Then, replace c with the index number (STATA uses 1 indexing) if it is still an empty string. Then list the results of c in a table without observation numbers or headers.

Only works in the "real" STATA interpreter. I need to add functions and conditions to the online interpreter for it to work there.

A different solution in 116 bytes:

forv x=1/100{
if!mod(`x',3){
di"Fizz"_c
if!mod(`x',5) di"Buzz"_c
}
else if!mod(`x',5) di"Buzz"_c
else di `x' _c
di
}

This solution goes through a for loop and checks whether the loop variable is divisible by 3 or not. If it is, it prints "Fizz". Then it checks if it is divisible by 5 and prints "Buzz". Otherwise, it checks if it is divisible by 5 and prints "Buzz". If not, it prints the loop variable.

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

UniBasic, 106 bytes

FOR I=1 TO 100;D='';IF MOD(I,3)=0 THEN D='Fizz'
IF MOD(I,5)=0 THEN D:='Buzz'
IF D='' THEN D=I
CRT D;NEXT I
\$\endgroup\$
1
\$\begingroup\$

Windows Batch, 172

@setlocal enableDelayedExpansion&for /l %%N in (1 1 100) do @(set v=&set/a1/(%%N%%3^)||set v=Fizz&set/a1/(%%N%%5^)||set v=!v!Buzz&if defined v (echo !v!)else echo %%N)2>nul
\$\endgroup\$
1
\$\begingroup\$

OCaml, 106

for i=1to 100do
let(!)n=i mod n<1and p=Printf.printf
in!3&p"Fizz"=();!5&p"Buzz"=()or!3||p"%d"i=();p"
"done

Apparently this isn't a very good attempt as the shortest one on anarchy golf is only 97.

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

Scala, 90 bytes

for(i<-1 to 100)println{var s="";if(i%3==0)s="Fizz";if(i%5==0)s+="Buzz";if(s=="")i else s}
\$\endgroup\$
1
\$\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\$
1
  • \$\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
    Commented Oct 2, 2015 at 20:57
1
\$\begingroup\$

Groovy, 83 80 bytes

(1..100).each{def f=it%3,b=it%5;println!f&&!b?'FizzBuzz':!f?'Fizz':!b?'Buzz':it}
\$\endgroup\$
1
\$\begingroup\$

ShapeScript, 57 bytes

0'1+0?3%1<"Fizz"*1?5%1<"Buzz"*+"#0?"1?_1<*!@"
"@'554***!#

Try it online!

How it works

0          Push 0 (accumulator).
'          Push a string that, when evaluated, does the following:
  1+         Increment the accumulator.
  0?         Push a copy.
  3%1<       Check if the remainder of its division by 3 is zero.
  "Fizz"*    Push "Fizz" for True, "" for False.
  1?         Push another copy of the accumulator.
  5%1<       Check if the remainder of its division by 5 is zero.
  "Buzz"*    Push "Buzz" for True, "" for False.
  +          Concatenate the potential fizzes and buzzes.
  "          Push a string that, when evaluated, does the following:
    #          Discard the topmost stack item.
    0?         Push a copy of the item below it (accumulator).
  "
  1?         Push a copy of the concatenation.
  _1<        Check if its length is zero.
  *!         Execute "#0?" once for True, zero times for False.
  @          Swap the generated output with the accumulator.
  "          Push "\n".
  "
  @          Swap it with the accumulator.
'
554**      Push 5 * 5 * 4 = 100.
*!         Execute the '...' string 100 times.
#          Discard the accumulator.
\$\endgroup\$
1
\$\begingroup\$

Rust, 145 137 131 bytes

Golfed

fn main(){for i in 1..101{let s=i.to_string();println!("{}",match i%15{0=>"FizzBuzz",3|6|9|12=>"Fizz",5|10=>"Buzz",_=>&(s)[..]});}}

Ungolfed

fn main() {
    for i in 1..101 {
        let s = i.to_string();
        println!("{}", match i % 15 {
            0        => "FizzBuzz",
            3|6|9|12 => "Fizz",
            5|10     => "Buzz",
            _        => &(s)[..]
        });
    }
}

Uses the current stable version of Rust (1.5.0).

\$\endgroup\$
1
  • \$\begingroup\$ You can remove a semicolon after println! call, as println! returns (). Also, it's possible to replace &(s)[..] with &s. \$\endgroup\$
    – null
    Commented Jul 6, 2018 at 7:53
1
\$\begingroup\$

Racket, 125 122 bytes

(for([x(range 1 101)])(define(m n)(=(modulo x n)0))(displayln(cond[(and(m 3)(m 5))'FizzBuzz][(m 3)'Fizz][(m 5)'Buzz][x])))

Simplest approach, took some work to get it lower than 130 bytes. Inspired by the Java example.

Pretty-printed code

(for ([x (range 1 101)])
  (define (m n)
    (= (modulo x n) 0))
  (displayln (cond
               [(and (m 3) (m 5)) 'FizzBuzz]
               [(m 3) 'Fizz]
               [(m 5) 'Buzz]
               [x])))
\$\endgroup\$
1
\$\begingroup\$

TCL, 208 bytes

Golfed:

set i 1;while {$i<101} {set p "";if {[expr $i % 3]==0} {set p [concat $p {fizz}]};if {[expr $i % 5]==0} {set p [concat $p {buzz}]};if {[expr $i % 3]>0&&[expr $i % 5]>0} {set p [concat $p $i]};puts $p;incr i;}

Ungolfed:

set i 1
while {$i<101} {
    set p ""
    if {[expr $i % 3]==0} {set p [concat $p {fizz}]}
    if {[expr $i % 5]==0} {set p [concat $p {buzz}]}
    if {[expr $i % 3]>0 && [expr $i % 5]>0} {set p [concat $p $i]}
    puts $p
    incr i
}
\$\endgroup\$
1
8 9
10
11 12
15

Your Answer

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

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