151
\$\begingroup\$

Introduction

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

Challenge

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

Output

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

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

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

Further Rules

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

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

  • Nothing can be printed to STDERR.

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

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

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

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

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

  • Standard loopholes are otherwise disallowed.

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

Catalogue

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

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

268 Answers 268

5
\$\begingroup\$

Groovy, 69 Bytes

(1..100).each{i->println i%15?(i%5?(i%3?i:'Fizz'):'Buzz'):'FizzBuzz'}
\$\endgroup\$
  • 2
    \$\begingroup\$ Can save 2 bytes using 1.upto(100){} and no parenthesis are needed in your answer, resulting in: 1.upto(100){i->println i%15?i%5?i%3?i:'Fizz':'Buzz':'FizzBuzz'}​ +1 though :). \$\endgroup\$ – Magic Octopus Urn Oct 13 '16 at 17:49
5
\$\begingroup\$

Transact-SQL, 163 143 124 110 bytes

This requires SQL Server 2012+

(thanks MickyT for the unnamed variable and the IIF suggestions, changed to muqo's GOTO loop instead of WHILE)

declare @ int=1a:print iif(@%3*@%5>0,ltrim(@),iif(@%3=0,'Fizz','')+iif(@%5=0,'Buzz',''))set @+=1IF @<101GOTO a

Formatted and explained:

declare @ int=1                      --@ is a valid variable name
a:                                   --shorter than WHILE
    print iif(@%3*@%5>0, ltrim(@),   --ltrim is shorter than explicit cast
          iif(@%3=0,'Fizz','')       --nest the IIFs
        + iif(@%5=0,'Buzz',''))
    set @+=1
IF @<101 GOTO a
\$\endgroup\$
  • \$\begingroup\$ Hello, and welcome to PPCG! Great answer! Can you please add an explanation? \$\endgroup\$ – NoOneIsHere May 6 '16 at 2:06
  • \$\begingroup\$ Sure thing I'll include the ungolfed version, it's just a while loop \$\endgroup\$ – Phrancis May 6 '16 at 2:06
  • \$\begingroup\$ I feel a bit privileged that in many languages you can't use expressions in case statements, but also a bit sad that the Oracle SQL person got fewer bytes... \$\endgroup\$ – Phrancis May 6 '16 at 6:15
  • 1
    \$\begingroup\$ Good work, but this needs more golfing. Use GOTO, not WHILE. Skip CONCAT because you need to force only @ to be a string, so just enclose it in LTRIM or something. Use + for the Fizz and Buzz IIFs, and nest that in the IIF for the other numbers. Remove as many spaces as possible. I can get your entry down to 110 doing all that. \$\endgroup\$ – Muqo Jul 21 '16 at 13:59
  • 1
    \$\begingroup\$ Code and explanation didn't match. Took the opportunity to edit in @Muqo's suggestions. \$\endgroup\$ – BradC Apr 19 '18 at 17:32
5
\$\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\$
  • \$\begingroup\$ for i in {1..100}\n{for((;100>i++;)){ \$\endgroup\$ – primo Nov 21 '18 at 14:59
  • 1
    \$\begingroup\$ @primo Thanks! Found a way to save one more. \$\endgroup\$ – Dennis Nov 21 '18 at 23:05
5
\$\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\$
  • \$\begingroup\$ Using < instead of ~: saves a byte \$\endgroup\$ – Bolce Bussiere Apr 6 at 16:42
  • 1
    \$\begingroup\$ And (;,>)Fizz`Buzz instead of 'Fizz'(,>@;;)'Buzz' saves another 5 \$\endgroup\$ – Bolce Bussiere Apr 6 at 16:56
  • 1
    \$\begingroup\$ @BolceBussiere < instead of :~:? \$\endgroup\$ – ASCII-only Apr 8 at 4:17
  • \$\begingroup\$ @ASCII-only the first : belongs to the verb 0: that returns the constant 0. The verb ~: represents 'not equal' \$\endgroup\$ – Bailis Cremey Apr 9 at 17:29
  • \$\begingroup\$ Idk, using just constant 0 worked for me \$\endgroup\$ – ASCII-only Apr 9 at 23:02
5
\$\begingroup\$

Seed, 6015 bytes

186 83944644497775792185807323999861330742900673481712359255839929374667216476568023851764637813248013688693896717275687232066153870107749175160194707761486575005885313952906442913325967953944535811512056079183251514390746052490451307246213606447865255212286265116943188690839445165359981774554198082946825007384980162551436390435260155582466874315352220541140434954811560506556477075852586817070090764184077321583489797358147025926992986354865415277367374043398355163643621296927936732212800075642321038031920620549375319366961667358107695950468557182519902148699776620624078332688843597417318685229781090303723160175745852091928346724348001020777912570918121340035523698691520422590527296248455779012094897281946771732844646467975422651655880202725095981882371807518829844157636552230152953535332201239998966830698645115246907049972204010095894629001206397276344975636564553238199728981112245810583644580269593382612869323054013019350314231784293448249910440692956496060253971880373279161390518237118507378691330341470412624728172421405109963475552981299919837091765136501358887135317778357279769289706821629750840213676581513947891276551415821187603189444230553630205086966993211879390093045277089486589385876312541940492767981701353769007246001400130719416118275492304807198011860072050303044225722194337717896831470037434122578382321765362062455130027125953869723625862069785410531287781468150359623495258126317807476517184801674197008747267394632928708383370640309530427431150403028006421518064783676469959724647961395869176187323826585310379142853088186864023708457159764123364029018721951815248751431170413579315400528983481702298849209797951129827235189965388114007169146563257209800975334610910397591190300324319540160364733177122449656422045835924029442449258975425381755648345550014417207471617919736685787448764321614059138375253980386335770138273578332418379763049794151811098188219754733324389355566317376598492318359989945589480418455750455469859956801589082779968271578522034926104268403877968397758570110853038536860556853388613997493905742068279137736678857073233174739380697685907170886092925173057794582407478105690770633669349947638020604803238951194381273510993928897230197983256465537488284258216944902276278712201715008765995404107536372438956009631805114079400698265046614085687812688769068889878215788959245601084883372435344000194364054441952170474833494604130017222942459218768152451353838900515646024764453476453552863938005162079649698291854043301771100462916706520075039044805956181705047266329114921035274711980897862579454154525144505597823262540025190878917613039796282312555295659294071407630514652646787462515667390800389392114746442068094785615537685660298361617697365653764669207754605147347324074541222276275532258194690926246437097055706104108319469003781845674958634242078791475826910418111428349167152839025683587469305219626924263962611094845308744968793376752461012553325189830937237777556407663277494722334379175044299145527685100424059993166500276116324651034389342857099326382267792125696063602436504279969923412378117936327869017861642388185619118723658181098871790872093500520584752433465443515989483851486224923341213990357424279098636563794743080022540640677640107176034203326304825856510242291526956869439836743210321616337131260522898066320086593786007891762080406650341513081903510025534886914361255147039463158189995500627220823997958074917925862170348467342212390436963261050291735696261617106196786273505443408966191019872244618002281427523777003325474230066462489531195157755555344637353155356279454281010364750875012491070816465270498678197434494849001514802132418781410405222031814823702582955264273367316636558580379660009282902598817700470535664545017234816209988594892835104965686956867851308392004044845547855039571721575449154495443479356960829759209226823917197487855397504141411230632224369201022681688301238065753737278463677847356448662974398206270856674118500884955014781944009536761710654880983265123955150729759406311220705702903728217724237231225228243114081826682040349685205121446193821261139703572900811243143912445467975694459999888915923116875430564637390061881889161512304819029656014338113772447267072899546161543780769850725712979853265124144813517511575434597175140160445249538753447856073028845070404104820699013418827593400549228758486817648053770622330987136941236768786640613654490823959024174575959620155957372041756651311988259843620347948677131103848960623371212015137053539005334518693964703094514744873758157905983139622925587291886231049371800498250086745691716656644176053612172113439907334397406577774498757112425437339205922869531575921611548158798375762386782843394828401126984185115349224303420458491251207091698634206841378497320259972637725826224808114267917428717816623368840721796784587349258491132128347823644310226457190477267965710821892576687103122134712656694901146343938508484308662925632874468476850854977933467327214644382364732022885458172449643330918925157997124690072012401561398600599725096512808715148150880033416494352767432615596760722206416684175988533830899565642405659319720681197534141300323187308210290375660950200938389996580887564670049743784962037885099514826194024014058093062057706139814777110125812527054724707373942053107785831307633110641398607263726549612409340127167852023607787965086360296071952107945138419803900924977980375619565210182772121849111987355981226968062629667279278470647719759267716675652568099185449478479471691254158308189631416224208590609150412906273490206303890853713104183863050119383440553687111132467944761189779633340481533657859382354192428154204487886313458547651002779223927726608436086877353829832057341247094095114657693381028772025327489391112902949559367893876211447144802835381133403893955836438518252858893637260806405255643702579004661210305919494653119109150790218729956868835489222681506976514342204634574313468575534020458319909578144280137077342941741913678288702984697189445809519253013406175446129538246339672293879388869701830984873958965248

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Oh, my generator must have glitched. I'll look on this \$\endgroup\$ – Krzysztof Szewczyk Sep 8 at 11:46
  • \$\begingroup\$ @JoKing Well, I should have tested my stuff before. Now it works \$\endgroup\$ – Krzysztof Szewczyk Sep 8 at 12:25
4
\$\begingroup\$

Perl 6, 109 93 bytes

for$i(1..100){if($i%3<1){say"Fizz"};if($i%5<1){say"Buzz"};if($i%3>0&&$i%5>0){say$i};say"\n";}

There might be some more golfing potential here.
Takes advantage the fact that 0 is the only way x % y can be less than 1 (thanks to Alex. A for shaving off 4 bytes with this) and Perl 6's say keyword.

\$\endgroup\$
  • \$\begingroup\$ I didn't spot this somehow... Sorry, If you'd like to adopt some of the ideas in my answer you can save more bytes! say is available in Perl 5 too for free (meta.codegolf.stackexchange.com/q/273#answer-274) and it includes a newline (which would further shorten mine by 5 bytes). Happy to remove mine (since it's newer than yours). \$\endgroup\$ – Dom Hastings Sep 24 '15 at 20:26
4
\$\begingroup\$

PowerShell, 59 58 bytes

Original used array selection, but was one byte longer than a minor variation of TimmyD's answer

old: 1..100|%{@($_,"Fizz","Buzz","FizzBuzz")[!($_%3)+2*!($_%5)]}

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

The only real trick involving use of double negation to make anything non-zero a 1 while leaving a zero a zero.

I would have left this as a comment on TimmyD's answer, but I lack the reputation.


EDIT: GAH! I see, now, that the original array implementation was naive insofar as my not having read through the other solutions and realizing that it was already in use ... multiple times over. I leave it here, but shamefacedly admit my ignorance.

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! Nice to see another PowerShell user around. Neat trick with the array-indexing, and further proof that PowerShell is nothing if not flexible. Note that, in this particular instance, you don't need to prepend the @ symbol, since PowerShell treats any comma-separated list as an array, saving a byte on that guy and making the two the same length. See an update on my answer as well, incorporating other suggestions. \$\endgroup\$ – AdmBorkBork Sep 25 '15 at 13:08
4
\$\begingroup\$

SWI-Prolog, 109 bytes

forall(between(1,100,I),((I mod 3<1,print('Fizz');1=1),(I mod 5<1,print('Buzz');I mod 3>0,print(I);1=1),nl)).
\$\endgroup\$
4
\$\begingroup\$

Beam, 307 288 bytes

And now for the longest solution. I think I could compress this a bit more, but the brain is getting a little fried. I'm pretty happy I got it working though. Rearranged it slightly to gain a few.

+P'++P'++P'''''''>`++ \/+)@'''''>`+++++++)@' \
v```P'''----(+++++++++/+/P+++'L@@++(+++++`<''/
>'p-`n'''''''>`++++++++/
^    >'P'p-``n'         >'p-``n'''''''''''>`++++++)@'''''''>`++ \
^       <    >p:L''p-``       >''P``v
^      Hu```P-p'''L@++++++++++LP+p  <``P+++++''L@@+++++@++(+++++/

var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";

var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;

function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}

function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}

function interrupt() {
error(ERROR_INTERRUPT);
}

function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}

function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;

code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;
	
code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
	if (code[i].length > width){ 
		width = code[i].length;
	}
}
console.log(code);
console.log(width);
	
running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];
	
input = input.split("").map(function (s) {
		return s.charCodeAt(0);
	});
	
iterations = 0;

beam_iter();
}

function beam_iter() {
while (running) {
	var inst; 
	try {
		inst = code[ip_y][ip_x];
	}
	catch(err) {
		inst = "";
	}
	switch (inst) {
		case ">":
			dir = 0;
			break;
		case "<":
			dir = 1;
			break;
		case "^":
			dir = 2;
			break;
		case "v":
			dir = 3;
			break;
		case "+":
			++beam;
			break;
		case "-":
			--beam;
			break;
		case "@":
			document.getElementById("output").value += String.fromCharCode(beam);
			break;
		case ":":
			document.getElementById("output").value += beam;
			break;
		case "/":
			dir ^= 2;
			break;
		case "\\":
			dir ^= 3;
			break;
		case "!":
			if (beam != 0) {
				dir ^= 1;
			}
			break;
		case "?":
			if (beam == 0) {
				dir ^= 1;
			}
			break;
		case "|":
			switch (dir) {
			case 2:
				dir = 3;
				break;
			case 3:
				dir = 2;
				break;
			}
			break;
		case "_":
			switch (dir) {
			case 0:
				dir = 1;
				break;
			case 1:
				dir = 0;
				break;
			}
			break;
		case "H":
			stop();
			break;
		case "S":
			store = beam;
			break;
		case "L":
			beam = store;
			break;
		case "s":
			mem[beam] = store;
			break;
		case "g":
			store = mem[beam];
			break;
		case "P":
			mem[store] = beam;
			break;
		case "p":
			beam = mem[store];
			break;
		case "u":
			if (beam != store) {
				dir = 2;
			}
			break;
		case "n":
			if (beam != store) {
				dir = 3;
			}
			break;
		case "`":
			--store;
			break;
		case "'":
			++store;
			break;
		case ")":
			if (store != 0) {
				dir = 1;
			}
			break;
		case "(":
			if (store != 0) {
				dir = 0;
			}
			break;
		case "r":
			if (input_ptr >= input.length) {
				beam = 0;
			} else {
				beam = input[input_ptr];
				++input_ptr;
			}
			break;
		}
	// Move instruction pointer
	switch (dir) {
		case 0:
			ip_x++;
			break;
		case 1:
			ip_x--;
			break;
		case 2:
			ip_y--;
			break;
		case 3:
			ip_y++;
			break;
	}
	if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
		error(ERROR_LOSTINSPACE);
	}
	++iterations;
	if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
		error(ERROR_TIMEOUT);
	}
}
}
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:
    <br>
    <textarea id="code" rows="6" style="overflow:scroll;overflow-x:hidden;width:90%;">+P'++P'++P'''''''>`++ \/+)@'''''>`+++++++)@' \
v```P'''----(+++++++++/+/P+++'L@@++(+++++`<''/
>'p-`n'''''''>`++++++++/
^    >'P'p-``n'         >'p-``n'''''''''''>`++++++)@'''''''>`++ \
^       <    >p:L''p-``       >''P``v
^      Hu```P-p'''L@++++++++++LP+p  <``P+++++''L@@+++++@++(+++++/
	</textarea>
        <br>
        <input id="run" type="button" value="Run" onclick="run()">
        <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled">
        <input id="clear" type="button" value="Clear" onclick="clear_output()">&nbsp; <span id="stderr" style="color:red"></span>
    </p>Output:
    <br>
    <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>
    <br>Input:
    <br>
    <textarea id="input" rows="1" style="overflow:scroll;overflow-x:hidden;width:90%;"></textarea>
    <p>Timeout:
        <input id="timeout" type="checkbox" checked="checked">&nbsp;
        <br>    </div>

Explanation

+P'++P'++P'''''''>`++ \
v```P'''----(+++++++++/

Initializes the program, presetting values in memory
Memory 0, value 1, count incrementer
Memory 1, value 3, div 3 decrementer
Memory 2, value 5, div 5 decrementer
Memory 3, value 99, loop decrementer

>'p-`n
     >'P'p-``n        
             >p:L''p-`` 

Gets value from Memory 1, decrements it, sets Store to 0. If value <> 0 change direction down, otherwise pass though.
Do the same with Memory 2. Finally if it gets down there, print out the current counter from memory 0.

                       /+)@'''''>`+++++++)@' \
                       +/P+++'L@@++(+++++`<''/
      '''''''>`++++++++/

Prints Fizz and resets memory slot 1 to 3.

                    >'p-``n'''''''''''>`++++++)@'''''''>`++ \

                                 ``P+++++''L@@+++++@++(+++++/

Another div 5 checker to catch FizzBuzzs. Prints out Buzz and resets memory slot 2 to 5.

                              >''P``v
       Hu```P-p'''L@++++++++++LP+p  <

Increments the counter, prints a newline, decrements the loop counter and exits if required.

\$\endgroup\$
4
\$\begingroup\$

MATLAB, 94 bytes

for i=1:100 t=mod(i,3);f=mod(i,5);s=[(t&f)*num2str(i) ~t*'Fizz' ~f*'Buzz' ''];disp(s(s>0));end

So this new code is a slight improvement on the one below. Rather than using arrayfun() which is quite costly in characters as it requires 'UniformOutput','false' to get it to work, I have simply made it a for loop - because the range of numbers is hard coded, there is no need to use a function as I had done in my last edit. Removing it from the function saves another 10 characters.

This does basically the same thing, but rather than making all the strings first, in makes them one by one in a for loop and displays them. This actually also means char() only has to be used once (in the other one it was used a second time to display everything). Having the loop means I can use variables to store the results of mod(i,3) and mod(i,5) so they don't need calculating twice. The nonzeros() function has also now been removed, instead opting for storing to a variable then only printing anything which is not equal to zero. This solution when you run it also doesn't print ans= before the first line.

Thanks to @flawr for the tips, saved 4 bytes.


Old code:

MATLAB, 118 bytes

char(arrayfun(@(x) char(nonzeros([(mod(x,3)&&mod(x,5))*num2str(x) ~mod(x,3)*'Fizz' ~mod(x,5)*'Buzz'])'),1:100,'Un',0))

A bit of fun with multiplying strings with scalars. Basically the output of ~mod(x,5) and ~mod(x,3) are multiplied by 'Fizz' and 'Buzz' respectively which produces either zeros (blanks) or one or both of the words. (mod(x,3)&&mod(x,5))) is basically when the number is neither a multiple of 3 nor 5 which is multiplied by the number as a string to get either zeros or the number.

These are then concatenated into an array which then has all of the zeros removed using nonzeros() and then resulting array transposed to be in the right direction for conversion to a character string.

Finally once all numbers have been processed by arrayfun(), the resulting cell array of arrays is passed to char() which converts it to a cell array of strings. Because there is no ; at the end of the string, the output is dumped to the console.


It might be possible to make it smaller, I'm looking ;)

\$\endgroup\$
  • \$\begingroup\$ I like your solution! Just some hints, you can use [s,''] instead of char(s) (I'd add that in the disp.) Then if you have arguments like UniformOutput it usually suffices to just write U or Un (just as many letters needed for discerning the different possible arguments) and instead of true,false you can use 1,0 (or for true any finite value bigger but zero). This also means instead of s~=0 you can use ~s or if this does not work s>0 or s<0 depending on the application. \$\endgroup\$ – flawr Sep 25 '15 at 22:50
  • \$\begingroup\$ @flawr Thanks for the tips. I hadn't realised that appending '' converted to a char string. I've saved 4 more bytes. Added the '' to the s=[ ] bit as it does the same as adding it in disp() but without the cost of the extra []. Also the s>0 was a bit of a duh moment on my part! \$\endgroup\$ – Tom Carpenter Sep 26 '15 at 4:29
  • \$\begingroup\$ There is a Tipps for golfing in Matlab (and linked there one for golfing in Octave) might be worth reading (and expanding=). Happy golfing=) \$\endgroup\$ – flawr Sep 26 '15 at 10:04
4
\$\begingroup\$

Lua, 88 86 bytes

Saved 2 bytes thanks to @Mauris

I'm sure this can be golfed more, any suggestions are welcome.

for i=1,100 do n=(i%3<1 and"Fizz"or"")..(i%5<1 and"Buzz"or"")print(n~=""and n or i)end
\$\endgroup\$
  • \$\begingroup\$ Try i%3<1 and i%5<1? \$\endgroup\$ – Lynn Sep 26 '15 at 22:25
  • \$\begingroup\$ 82 bytes: for i=1,100 do s=('Fizz'):sub(i%3*5)..('Buzz'):sub(i%5*5)print(s==''and i or s)end \$\endgroup\$ – Lynn Sep 27 '15 at 21:56
  • \$\begingroup\$ I posted a 72-byte solution that ties the record on anarchy golf. \$\endgroup\$ – Lynn Sep 27 '15 at 22:19
4
\$\begingroup\$

Python 3, 59 bytes

Based on @feersum's answer.

for i in range(100):print(i%3//2*"fizz"+i%5//4*"buzz"or-~i)
\$\endgroup\$
4
\$\begingroup\$

C (83 characters)

Because misusing a (POSIX conformant) printf is not that bad, after all:

i;main(){while(++i<101)printf(i%3?i%5?"%2$d\n":"%s\n":"Fizz%s\n",i%5?"":"Buzz",i);}
\$\endgroup\$
4
\$\begingroup\$

Gol><>, 40 bytes

`e2RFL5%zR"zzuB"L3%zR"zziF"lQlRoaoC|LN|;

Updated for 0.4.0! I'm still tinkering with loops and trying to figure out how to do things best, but this is looking good so far.

Try it online.

Explanation

`e            Push 'e', or 101
2RF ... |     Execute F for loop twice - the first time activates the loop, and the
              second time updates it. This effectively makes the loop start from 1
L5%z          Push 1 if loop counter % 5 is 0, else 1
R"zzuB"       Push "Buzz" (top of stack) number of times
L3%z          Push 1 if loop counter % 3 is 0, else 1
R"zziF"       Push "Fizz" (top of stack) number of times
lQ ... |      If the stack is not empty...
  lRo         Output stack
  ao          Output newline
  C           Continue for loop
LN            Otherwise, print loop counter with newline

;             Terminate program

As we can see, there's a lot of abuse of R, which pops the top of the stack and executes the next instruction that many times.

\$\endgroup\$
  • \$\begingroup\$ That's a smart idea! Mind if I use it? \$\endgroup\$ – Conor O'Brien Oct 28 '15 at 12:16
4
\$\begingroup\$

Perl 6, 46 bytes

say "Fizz"x $_%%3~"Buzz"x $_%%5||$_ for 1..100
\$\endgroup\$
  • 2
    \$\begingroup\$ You can remove the spaces after x \$\endgroup\$ – Jo King Jan 6 at 3:27
4
\$\begingroup\$

Seriously, 36 bytes

2╤R`;;3@%Y"Fizz"*)5@%Y"Buzz"*(+;I`Mi

Explanation:

2╤   push the value 10**2 (100)
R       pop a: push range(1,a+1)
`       start function literal
  ;;      duplicate the top of the stack twice
  3       push the value 3
  @       swap the top 2 values
  %       pop a,b: push a%b
  Y       pop a: push 1 if a==0, else 0
  "Fizz"  push the string "Fizz"
  *       pop a,b: push a*b (in this case, "Fizz" repeated b times)
  )       rotate the stack right by one ([a,b,c] -> [c,a,b])
  5@%Y"Buzz"*   Do the same thing as above, but with divisibility testing for 5 and using "Buzz"
  (       rotate the stack left by one
  +       pop a,b: push a+b (string concatenation here)
  ;       dupe top of stack
  I       pop a,b,c: push b if a is truthy, else c (here, a and b are the same string, either "", "Fizz", "Buzz", or "FizzBuzz", and c is the original integer)
`       end function literal
M       pop f,[a]: using each element of [a] as a temporary stack, evaluate f, and push the result
i       flatten [a] (push each value in [a] to the stack, starting from the end to preserve order)

Try it online.

\$\endgroup\$
  • \$\begingroup\$ Methinks you need a logical NOT in Seriously. \$\endgroup\$ – lirtosiast Nov 10 '15 at 23:11
  • \$\begingroup\$ @ThomasKwa Maybe. I was wishing it had one while I was writing this. Seriously has ~, which is unary bitwise negation, which is not quite the same thing. I might add one. \$\endgroup\$ – Mego Nov 10 '15 at 23:13
4
\$\begingroup\$

8086 machine code, 70 68 62 bytes

00000000  31 c0 40 50 89 c2 89 e5  68 0a 24 d4 05 75 06 68  |1.@P....h.$..u.h|
00000010  7a 7a 68 42 75 89 d0 d4  03 75 06 68 7a 7a 68 46  |zzhBu....u.hzzhF|
00000020  69 89 d0 83 fc fa 75 08  d4 0a 86 c4 0d 30 30 50  |i.....u......00P|
00000030  b4 09 89 e2 cd 21 89 ec  58 3c 64 75 c5 c3        |.....!..X<du..|
0000003e

How it works:

            |   org 0x100
            |   use16
31 c0       |       xor ax, ax
40          |   aa: inc ax
50          |       push ax
89 c2       |       mov dx, ax
89 e5       |       mov bp, sp
68 0a 24    |       push 0x240a
d4 05       |       aam 5
75 06       |       jnz @f
68 7a 7a    |       push 0x7a7a
68 42 75    |       push 0x7542
89 d0       |   @@: mov ax, dx
d4 03       |       aam 3
75 06       |       jnz @f
68 7a 7a    |       push 0x7a7a
68 46 69    |       push 0x6946
89 d0       |   @@: mov ax, dx
83 fc fa    |       cmp sp, -6
75 08       |       jne @f
d4 0a       |       aam 10
86 c4       |       xchg al, ah
0d 30 30    |       or ax, 0x3030
50          |       push ax
b4 09       |   @@: mov ah, 0x09
89 e2       |       mov dx, sp
cd 21       |       int 0x21
89 ec       |       mov sp, bp
58          |       pop ax
3c 64       |       cmp al, 100
75 c5       |       jne aa
c3          |       ret
\$\endgroup\$
  • \$\begingroup\$ This is very nice and very clean work! Using the stack is quite elegant! Technically PUSH immediate was not available on the 8086, so this is really 80186+ machine code. Also, not sure if it's allowed or not, but this does show leading 0's on single digit numbers (01 02 Fizz 03, etc). \$\endgroup\$ – 640KB Aug 28 at 1:04
4
\$\begingroup\$

Fortran, 188 bytes

do i=1,100
if(mod(i,3)==0.and.mod(i,5)==0)then;print'(a)','fizzbuzz'
elseif(mod(i,3)==0)then;print'(a)','fizz'
elseif(mod(i,5)==0)then;print'(a)','buzz'
else;print'(i0)',i
end if;enddo;end
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Aug 3 '17 at 15:32
  • 1
    \$\begingroup\$ ...change print'(a)' etc. to print* to save 16 bytes \$\endgroup\$ – roblogic Apr 5 at 14:49
  • \$\begingroup\$ I never used print* as it prints the characters with a space or two before hand, thus it doesn't match the required format. \$\endgroup\$ – lewisfish Apr 15 at 14:09
4
\$\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\$
4
\$\begingroup\$

Pip, 32 31 bytes

LhP J["Fizz""Buzz"]X!*++i%^35|i

Try it online!

Explanation

LhP J["Fizz""Buzz"]X!*++i%^35|i
                                 Preinitialized variables: h=100, i=0
Lh                               Loop 100 times:
                          ^35     Split 35 into a list of digits: [3 5]
                      ++i         Pre-increment i (thus starting at 1, not 0)
                         %        Mod (vectorizing); our list is now [i%3 i%5]
                    !*            Map logical not to that list (1 if mod was 0, else 0)
     ["Fizz""Buzz"]               List containing Fizz and Buzz 
                   X              Repeat string (vectorizing)
                                  Our two items are now:
                                   "Fizz" if i is divisible by 3, "" otherwise
                                   "Buzz" if i is divisible by 5, "" otherwise
    J                             Join that list into a single string
  P                          |i   Logical or with i, and print
\$\endgroup\$
4
\$\begingroup\$

Befunge-93, 61 bytes

1+::::3%|>.#_:"c"`#@_55+,
,,:,,0\v>"ziF"
,:,,$01>>5%#v_"zuB",

Try it online!

Decided to come back to this and make it conform to specification while shaving some bytes off. Look, no extra spaces!

\$\endgroup\$
4
\$\begingroup\$

Brain-Flak, 474 470 446 438 420 412 bytes

-18 bytes thanks to Nitroden!

-8 thanks to Wheat Wizard

(((()()()()()){}){}){({}[(()())]((((())))))}{}{({}<>)<>({}<>)<>({}()()<>)<>}<>{}{}{([{}]())({()<(({}())()){(<{}>)((((()()()())())((((({}{}){})[()]){}){}()))){({}<>)<>}}{}{(<{}>)(((((()()()())({})){}())(({})({}())({}{})))){({}<>)<>}}>}{}[()]){([](<>))<>((()()()()()){}){(({}<({}())>)){({}[()])<>}{}}{}<>([{}()]{}<>)<>{({}<>)(<>)}}{}(<>)<>}<>{}{{({}((((()()()){}){}){}){}<>)<>}({}(()()()()()){}<>)<>}<>{({}<>)<>}<>

Try it online!

Gosh, it's nice to finally check this off my to-do list.

Explanation:

Brain-Flak is obviously not very good at getting the modulo of numbers, so I bypassed this by pushing all the elements first.

(((()()()()()){}){}) Push 20
{ Loop 20 times
    ({}
    [(()())]    Push a 2 to represent a Buzz
    ((((()))))  Push 4 1s
    ) And decrement loop counter
}{} Pop the excess 0
{ Loop over the list of numbers
    ({}<>)<>({}<>)<> Transfer two of the elements to the other stack
    ({}()()<>)<>     And add 2 to the last one
}<>{}{} Pop the excess two elements

Now 1 represents normal numbers, 2 represents Buzz, 3 is Fizz and 4 represents FizzBuzz. Initially I just pushed the values that repeat every 15 numbers 7 times and popped the excess 5, but this way turned out to be slightly shorter.

{ Loop over each element
    ([{}]()) Subtract one from the current element
    ({ Fizz and/or Buzz if num is not 1
        <(({}())())  Subtract 1 and push, twice
        { Push Buzz if num was not 3
            (<{}>)((((()()()())())((((({}{}){})[()]){}){}()))){({}<>)<>}
        }{}
        { Push Fizz if num is not 2
            (<{}>)(((((()()()())({})){}())(({})({}())({}{})))){({}<>)<>}
        }
        >
        ()
    }{}[()]) Push -1 if neither Fizz nor Buzz were pushed
    {
        ([](<>)) Push length of list to other stack
        <>((()()()()()){}) Push 10 as the mod
        Div/mod algorithm
        {(({}<({}())>)){({}[()])<>}{}}{}<>([{}()]{}<>)<>
        Pushes n%10 to output stack and n/10 to the list stack
        { If div is not 0
            ({}<>) Push it to the other stack
            (<>)   Push 0
        }
    }{} Pop excess 0
    (<>)<> Push 0 to other stack to represent a newline
}<>{} Pop extra newline
{ Loop over values
    {
        ({}((((()()()){}){}){}){}<>)<>  Add 48 to every value
    }
    ({}(()()()()()){}<>)<> Turn 0s into newlines
}  Until there's two 0s in a row
<>{({}<>)<>}<> Reverse output

\$\endgroup\$
4
\$\begingroup\$

SQL (Oracle), 112 108 bytes

SELECT NVL(DECODE(MOD(LEVEL,3),0,'Fizz')||DECODE(MOD(LEVEL,5),0,'Buzz'),LEVEL)FROM DUAL CONNECT BY LEVEL<101

db<>fiddle here

\$\endgroup\$
  • 1
    \$\begingroup\$ ''||LEVEL can be simple replaced with level \$\endgroup\$ – Dr Y Wit Aug 28 at 14:15
3
\$\begingroup\$

Mouse, 75 bytes

1I:(I.101<^0J:I.3\0=["Fizz"J.1+J:]I.5\0=["Buzz"J.1+J:]J.0=[I.!]"!"I.1+I:)$

Ungolfed:

1 I:               ~ Start a loop index at 1
( I. 101 < ^       ~ While I < 101...
  0 J:             ~ Begin a divisibility indicator at 0
  I. 3 \ 0 = [     ~ If I % 3 == 0
    "Fizz"         ~ Print "Fizz" to STDOUT
    J. 1 + J:      ~ Increment J
  ]
  I. 5 \ 0 = [     ~ If I % 5 == 0
    "Buzz"         ~ Print "Buzz" to STDOUT
    J. 1 + J:      ~ Increment J
  ]
  J. 0 = [         ~ If neither 3 nor 5 divides I
    I. !           ~ Print I to STDOUT
  ]
  "!"              ~ Print a newline
  I. 1 + I:        ~ Increment I
)
$
\$\endgroup\$
  • 1
    \$\begingroup\$ I'm gonna upvote if you add a cat-program. \$\endgroup\$ – flawr Sep 24 '15 at 20:16
  • 1
    \$\begingroup\$ @flawr You should submit your own cat program. It will be a game of cat and mouse. \$\endgroup\$ – Alex A. Sep 24 '15 at 20:44
  • 1
    \$\begingroup\$ @flawr Not quite cat, but I did add a zcat program. \$\endgroup\$ – Daniel Wagner Sep 25 '15 at 2:23
3
\$\begingroup\$

Processing, 74 bytes

This is based on the Java answer by Geobits. I converted it into Processing and since Processing is similar to Java, the code is a lot similar to Geobits'.

for(int i=0;i++<100;)println((i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":i));
\$\endgroup\$
  • 8
    \$\begingroup\$ Ah, Processing. Java's willful son, stubbornly insisting that he's going to grow up to be an artist :D \$\endgroup\$ – Geobits Sep 24 '15 at 20:24
3
\$\begingroup\$

Common Lisp, 121

(dotimes(x 100)(flet((d(n)(= 0(mod(1+ x)n))))(princ(cond((d 15)"FizzBuzz")((d 3)"Fizz")((d 5)"Buzz")(t(1+ x)))))(terpri))

Readable:

(dotimes (x 100)
  (flet ((d (n) (= 0 (mod (1+ x) n))))
    (princ (cond ((d 15) "FizzBuzz")
                 ((d 3) "Fizz")
                 ((d 5) "Buzz")
                 (t (1+ x)))))
  (terpri))
\$\endgroup\$
3
\$\begingroup\$

Ruby, 59

I wanted to make a Ruby version using the slick modulo/integer-division/string-multiplication trick from feersum's Python answer (though unfortunately Ruby doesn't handle string multiplication the same way, so I spent some bytes on that):

100.times{|i|puts "#{i+1}\r"+"Fizz"*(i%3/2)+"Buzz"*(i%5/4)}

Note that this uses a carriage return \r without a newline. I don't know how portable this is; it works on my Linux and should work on Linux in general, as well as on Mac, but I'm not sure how Windows handles it. Without that, here's a 61-byte version:

100.times{|i|puts ("Fizz"*(i%3/2)+"Buzz"*(i%5/4))[/.+/]||i+1}
\$\endgroup\$
  • \$\begingroup\$ You don't need space after puts. \$\endgroup\$ – Vasu Adari Dec 7 '15 at 3:20
3
\$\begingroup\$

Commodore Basic, 87 bytes

1F┌I=1TO100:F=F+1:B=B+1:IFF=3T|?"FIZZ";:F=0
2IFB=5T|?"BUZZ";:B=0
3IFF>0A/B>0T|?I;
4?:N─

Or in "shifted mode" to get both lower- and upper-case letters, but with the byte values of lowercase and uppercase swapped relative to ASCII-1967 (press COMMODORE+SHIFT):

1fOi=1to100:f=f+1:b=b+1:iff=3tH?"Fizz";:f=0
2ifb=5tH?"Buzz";:b=0
3iff>0aNb>0tH?i;
4?:nE

Usual PETSCII-to-Unicode substitutions: = SHIFT+O, | = SHIFT+H, / = SHIFT+N, = SHIFT+E

Commodore Basic doesn't have a "modulus" operation, so I need to use alternate methods to figure out when to print what: keeping a pair of counters turns out to be fewer bytes than dividing and checking for integer-ness. It also doesn't have a true logical "and" (despite the manual saying otherwise), so I need to do an explicit comparison against zero to decide if I should print the plain number.

\$\endgroup\$
  • \$\begingroup\$ @DLosc, you can switch into "shifted mode" which gives access to both upper- and lower-case, but with the character positions reversed relative to the ASCII-1967 which people are familiar with (eg. character #65 is lowercase "a" rather than uppercase). \$\endgroup\$ – Mark Sep 28 '15 at 2:27
3
\$\begingroup\$

Minkolang, 50 bytes

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

Try it here.

Explanation

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

Jolf, 42 33 31 bytes

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

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

Old version, 42 bytes

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

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

\$\endgroup\$

Your Answer

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

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