FizzBuzz: Difference between revisions
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
|||
Line 25: | Line 25: | ||
{{trans|Python3: Simple}} |
{{trans|Python3: Simple}} |
||
< |
<syntaxhighlight lang="11l">L(i) 1..100 |
||
I i % 15 == 0 |
I i % 15 == 0 |
||
print(‘FizzBuzz’) |
print(‘FizzBuzz’) |
||
Line 33: | Line 33: | ||
print(‘Buzz’) |
print(‘Buzz’) |
||
E |
E |
||
print(i)</ |
print(i)</syntaxhighlight> |
||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Line 51: | Line 51: | ||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth"> |
||
with: n |
with: n |
||
Line 77: | Line 77: | ||
' fizzbuzz 1 100 loop |
' fizzbuzz 1 100 loop |
||
cr bye |
cr bye |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
||
<syntaxhighlight lang="aarch64 assembly"> |
|||
<lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
/* ARM assembly AARCH64 Raspberry PI 3B */ |
||
/* program FizzBuzz64.s */ |
/* program FizzBuzz64.s */ |
||
Line 176: | Line 176: | ||
/* for this file see task include a file in language AArch64 assembly */ |
/* for this file see task include a file in language AArch64 assembly */ |
||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ABAP}}== |
=={{header|ABAP}}== |
||
===Impure Functional 1=== |
===Impure Functional 1=== |
||
{{works with|ABAP|7.4 SP05 or Above only}} |
{{works with|ABAP|7.4 SP05 or Above only}} |
||
< |
<syntaxhighlight lang="abap">DATA: tab TYPE TABLE OF string. |
||
tab = VALUE #( |
tab = VALUE #( |
||
Line 193: | Line 193: | ||
cl_demo_output=>write( tab ). |
cl_demo_output=>write( tab ). |
||
cl_demo_output=>display( ).</ |
cl_demo_output=>display( ).</syntaxhighlight> |
||
===Impure Functional 2=== |
===Impure Functional 2=== |
||
{{works with|ABAP|7.4 SP05 or Above only}} |
{{works with|ABAP|7.4 SP05 or Above only}} |
||
< |
<syntaxhighlight lang="abap">cl_demo_output=>display( value stringtab( for i = 1 until i > 100 |
||
let fizz = cond #( when i mod 3 = 0 then |fizz| else space ) |
let fizz = cond #( when i mod 3 = 0 then |fizz| else space ) |
||
buzz = cond #( when i mod 5 = 0 then |buzz| else space ) |
buzz = cond #( when i mod 5 = 0 then |buzz| else space ) |
||
fb = |{ fizz }{ buzz }| in |
fb = |{ fizz }{ buzz }| in |
||
( switch #( fb when space then i else fb ) ) ) ).</ |
( switch #( fb when space then i else fb ) ) ) ).</syntaxhighlight> |
||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun fizzbuzz-r (i) |
||
(declare (xargs :measure (nfix (- 100 i)))) |
(declare (xargs :measure (nfix (- 100 i)))) |
||
(prog2$ |
(prog2$ |
||
Line 215: | Line 215: | ||
(fizzbuzz-r (1+ i))))) |
(fizzbuzz-r (1+ i))))) |
||
(defun fizzbuzz () (fizzbuzz-r 1))</ |
(defun fizzbuzz () (fizzbuzz-r 1))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC Main() |
||
BYTE i,d3,d5 |
BYTE i,d3,d5 |
||
Line 239: | Line 239: | ||
IF d5=5 THEN d5=0 FI |
IF d5=5 THEN d5=0 FI |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/FizzBuzz.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/FizzBuzz.png Screenshot from Atari 8-bit computer] |
||
Line 252: | Line 252: | ||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
The [[ActionScript]] solution works just like the [[FizzBuzz#JavaScript|JavaScript]] solution (they share the [[ECMAScript]] specification). The difference is that ActionScript has the ''trace'' command to write out to a console. |
The [[ActionScript]] solution works just like the [[FizzBuzz#JavaScript|JavaScript]] solution (they share the [[ECMAScript]] specification). The difference is that ActionScript has the ''trace'' command to write out to a console. |
||
< |
<syntaxhighlight lang="actionscript">for (var i:int = 1; i <= 100; i++) { |
||
if (i % 15 == 0) |
if (i % 15 == 0) |
||
trace('FizzBuzz'); |
trace('FizzBuzz'); |
||
Line 261: | Line 261: | ||
else |
else |
||
trace(i); |
trace(i); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Fizzbuzz is |
procedure Fizzbuzz is |
||
Line 279: | Line 279: | ||
end if; |
end if; |
||
end loop; |
end loop; |
||
end Fizzbuzz;</ |
end Fizzbuzz;</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">main:( |
||
FOR i TO 100 DO |
FOR i TO 100 DO |
||
printf(($gl$, |
printf(($gl$, |
||
Line 296: | Line 296: | ||
)) |
)) |
||
OD |
OD |
||
)</ |
)</syntaxhighlight> |
||
or simply: |
or simply: |
||
< |
<syntaxhighlight lang="algol68">FOR i TO 100 DO print(((i%*15=0|"FizzBuzz"|:i%*3=0|"Fizz"|:i%*5=0|"Buzz"|i),new line)) OD</syntaxhighlight> |
||
=={{header|ALGOL-M}}== |
=={{header|ALGOL-M}}== |
||
< |
<syntaxhighlight lang="algolm">BEGIN |
||
INTEGER FUNCTION DIVBY(N, D); |
INTEGER FUNCTION DIVBY(N, D); |
||
Line 323: | Line 323: | ||
END; |
END; |
||
END</ |
END</syntaxhighlight> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw"> |
||
begin |
begin |
||
i_w := 1; % set integers to print in minimum space % |
i_w := 1; % set integers to print in minimum space % |
||
Line 335: | Line 335: | ||
else write( i ) |
else write( i ) |
||
end for_i |
end for_i |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|AntLang}}== |
=={{header|AntLang}}== |
||
< |
<syntaxhighlight lang="antlang">n:{1+ x}map range[100] |
||
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n |
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n |
||
echo map s</ |
echo map s</syntaxhighlight> |
||
=={{header|APEX}}== |
=={{header|APEX}}== |
||
<syntaxhighlight lang="apex"> |
|||
<lang Apex> |
|||
for(integer i=1; i <= 100; i++){ |
for(integer i=1; i <= 100; i++){ |
||
String output = ''; |
String output = ''; |
||
Line 354: | Line 354: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl">⎕IO←0 |
||
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100] |
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Slightly different approach that makes use of the Decode function (⊥): |
Slightly different approach that makes use of the Decode function (⊥): |
||
< |
<syntaxhighlight lang="apl"> |
||
A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100] |
A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100] |
||
</syntaxhighlight> |
|||
</lang> |
|||
The idea is to first calculate the residues for all numbers 1..100 after |
The idea is to first calculate the residues for all numbers 1..100 after |
||
Line 387: | Line 387: | ||
Here's a Dyalog-specific solution taking advantage of its anonymous function extension: |
Here's a Dyalog-specific solution taking advantage of its anonymous function extension: |
||
< |
<syntaxhighlight lang="apl">{ ⍵ 'Fizz' 'Buzz' 'FizzBuzz'[ +/1 2×0=3 5|⍵] }¨1+⍳100</syntaxhighlight> |
||
A slightly different version that works both in Dyalog and GNU APL -- credit to Aniket Bhattacharyea, posted on codeburst.io (https://codeburst.io/fizzbuzz-in-apl-a193d1954b4b): |
A slightly different version that works both in Dyalog and GNU APL -- credit to Aniket Bhattacharyea, posted on codeburst.io (https://codeburst.io/fizzbuzz-in-apl-a193d1954b4b): |
||
< |
<syntaxhighlight lang="apl">{(‘FizzBuzz’ ‘Fizz’ ‘Buzz’,⍵)[(0=15 3 5|⍵)⍳1]}¨⍳100</syntaxhighlight> |
||
Yet another solution, excessively commented: |
Yet another solution, excessively commented: |
||
Line 397: | Line 397: | ||
{{works with|GNU_APL}} (and Dyalog, with [http://course.dyalog.com/autumn2021/Quirks/ ⎕ML ← 2]) |
{{works with|GNU_APL}} (and Dyalog, with [http://course.dyalog.com/autumn2021/Quirks/ ⎕ML ← 2]) |
||
< |
<syntaxhighlight lang="apl"> ∇ sv ← fizzbuzz n; t;d |
||
[1] ⍝⍝ Solve the popular 'fizzbuzz' problem in APL. |
[1] ⍝⍝ Solve the popular 'fizzbuzz' problem in APL. |
||
[2] ⍝⍝ \param n - highest number to compute (≥0) |
[2] ⍝⍝ \param n - highest number to compute (≥0) |
||
Line 436: | Line 436: | ||
[37] ⍝⍝ ⎕ ← ,fizzbuzz 15 |
[37] ⍝⍝ ⎕ ← ,fizzbuzz 15 |
||
[38] ⍝ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz |
[38] ⍝ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz |
||
∇</ |
∇</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
===Procedural=== |
===Procedural=== |
||
< |
<syntaxhighlight lang="applescript">property outputText: "" |
||
repeat with i from 1 to 100 |
repeat with i from 1 to 100 |
||
if i mod 15 = 0 then |
if i mod 15 = 0 then |
||
Line 453: | Line 453: | ||
set outputText to outputText & linefeed |
set outputText to outputText & linefeed |
||
end repeat |
end repeat |
||
outputText</ |
outputText</syntaxhighlight> |
||
---- |
---- |
||
If this were a useful task requiring a degree of efficiency, it would be better to replace the cumulative text concatenations with additions to a fast-to-access list and coerce this list to text in one go at the end. Less critically, the <tt>(i mod … = 0)</tt> tests could be nested to reduce the number of these performed from 261 to 200: |
If this were a useful task requiring a degree of efficiency, it would be better to replace the cumulative text concatenations with additions to a fast-to-access list and coerce this list to text in one go at the end. Less critically, the <tt>(i mod … = 0)</tt> tests could be nested to reduce the number of these performed from 261 to 200: |
||
< |
<syntaxhighlight lang="applescript">on fizzBuzz(n) |
||
script o |
script o |
||
property output : {} |
property output : {} |
||
Line 484: | Line 484: | ||
end fizzBuzz |
end fizzBuzz |
||
fizzBuzz(100)</ |
fizzBuzz(100)</syntaxhighlight> |
||
Another alternative would be simply to fill the list with numbers and then go through it again three times overwriting the relevant slots with the appropriate words: |
Another alternative would be simply to fill the list with numbers and then go through it again three times overwriting the relevant slots with the appropriate words: |
||
< |
<syntaxhighlight lang="applescript">on fizzBuzz(n) |
||
script o |
script o |
||
property output : {} |
property output : {} |
||
Line 511: | Line 511: | ||
end fizzBuzz |
end fizzBuzz |
||
fizzBuzz(100)</ |
fizzBuzz(100)</syntaxhighlight> |
||
With the number of numbers raised from 100 to 10,000, the two scripts inserted here take around 0.051 seconds to execute on my current machine, the original AppleScript above around 0.25 seconds, and the one below (originally described as "functional composition") 3.52 seconds. |
With the number of numbers raised from 100 to 10,000, the two scripts inserted here take around 0.051 seconds to execute on my current machine, the original AppleScript above around 0.25 seconds, and the one below (originally described as "functional composition") 3.52 seconds. |
||
Line 517: | Line 517: | ||
===Functional=== |
===Functional=== |
||
For simplicity, and more efficient use of the scripter's time: |
For simplicity, and more efficient use of the scripter's time: |
||
< |
<syntaxhighlight lang="applescript">------------------------- FIZZBUZZ ------------------------- |
||
-- fizz :: Int -> Bool |
-- fizz :: Int -> Bool |
||
Line 610: | Line 610: | ||
end script |
end script |
||
end if |
end if |
||
end mReturn</ |
end mReturn</syntaxhighlight> |
||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
Line 616: | Line 616: | ||
=={{header|Arbre}}== |
=={{header|Arbre}}== |
||
< |
<syntaxhighlight lang="arbre">fizzbuzz(): |
||
for x in [1..100] |
for x in [1..100] |
||
if x%5==0 and x%3==0 |
if x%5==0 and x%3==0 |
||
Line 630: | Line 630: | ||
main(): |
main(): |
||
fizzbuzz() -> io</ |
fizzbuzz() -> io</syntaxhighlight> |
||
=={{header|Arc}}== |
=={{header|Arc}}== |
||
===Arc 3.1 Base=== |
===Arc 3.1 Base=== |
||
< |
<syntaxhighlight lang="lisp">(for n 1 100 |
||
(prn:if |
(prn:if |
||
(multiple n 15) 'FizzBuzz |
(multiple n 15) 'FizzBuzz |
||
(multiple n 5) 'Buzz |
(multiple n 5) 'Buzz |
||
(multiple n 3) 'Fizz |
(multiple n 3) 'Fizz |
||
n))</ |
n))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(for n 1 100 |
||
(prn:check (string (when (multiple n 3) 'Fizz) |
(prn:check (string (when (multiple n 3) 'Fizz) |
||
(when (multiple n 5) 'Buzz)) |
(when (multiple n 5) 'Buzz)) |
||
~empty n)) ; check created string not empty, else return n</ |
~empty n)) ; check created string not empty, else return n</syntaxhighlight> |
||
===Waterhouse Arc=== |
===Waterhouse Arc=== |
||
< |
<syntaxhighlight lang="lisp">(for n 1 100 |
||
(prn:case (gcd n 15) |
(prn:case (gcd n 15) |
||
1 n |
1 n |
||
3 'Fizz |
3 'Fizz |
||
5 'Buzz |
5 'Buzz |
||
'FizzBuzz))</ |
'FizzBuzz))</syntaxhighlight> |
||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
<syntaxhighlight lang="arm_assembly"> |
|||
<lang ARM_Assembly> |
|||
/ * linux GAS */ |
/ * linux GAS */ |
||
Line 774: | Line 774: | ||
mov r0, r2 |
mov r0, r2 |
||
mov pc, lr |
mov pc, lr |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">loop 1..100 [x][ |
||
case [] |
case [] |
||
when? [0=x%15] -> print "FizzBuzz" |
when? [0=x%15] -> print "FizzBuzz" |
||
Line 783: | Line 783: | ||
when? [0=x%5] -> print "Buzz" |
when? [0=x%5] -> print "Buzz" |
||
else -> print x |
else -> print x |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>1 |
<pre>1 |
||
Line 893: | Line 893: | ||
=={{header|Asymptote}}== |
=={{header|Asymptote}}== |
||
< |
<syntaxhighlight lang="asymptote">for(int number = 1; number <= 100; ++number) { |
||
if (number % 15 == 0) { |
if (number % 15 == 0) { |
||
write("FizzBuzz"); |
write("FizzBuzz"); |
||
Line 907: | Line 907: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ATS}}== |
=={{header|ATS}}== |
||
< |
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats" |
||
implement main0() = loop(1, 100) where { |
implement main0() = loop(1, 100) where { |
||
Line 927: | Line 927: | ||
loop(from+1, to) |
loop(from+1, to) |
||
end |
end |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
{{AutoHotkey case}} |
{{AutoHotkey case}} |
||
< |
<syntaxhighlight lang="autohotkey">Loop, 100 |
||
{ |
{ |
||
If (Mod(A_Index, 15) = 0) |
If (Mod(A_Index, 15) = 0) |
||
Line 944: | Line 944: | ||
FileDelete, output.txt |
FileDelete, output.txt |
||
FileAppend, %output%, output.txt |
FileAppend, %output%, output.txt |
||
Run, cmd /k type output.txt</ |
Run, cmd /k type output.txt</syntaxhighlight> |
||
A short example with cascading ternary operators and graphical output. Press Esc to close the window. |
A short example with cascading ternary operators and graphical output. Press Esc to close the window. |
||
< |
<syntaxhighlight lang="autohotkey">Gui, Add, Edit, r20 |
||
Gui,Show |
Gui,Show |
||
Loop, 100 |
Loop, 100 |
||
Line 952: | Line 952: | ||
Return |
Return |
||
Esc:: |
Esc:: |
||
ExitApp</ |
ExitApp</syntaxhighlight> |
||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
===Example1=== |
===Example1=== |
||
Output via MsgBox(): |
Output via MsgBox(): |
||
< |
<syntaxhighlight lang="autoit">For $i = 1 To 100 |
||
If Mod($i, 15) = 0 Then |
If Mod($i, 15) = 0 Then |
||
MsgBox(0, "FizzBuzz", "FizzBuzz") |
MsgBox(0, "FizzBuzz", "FizzBuzz") |
||
Line 967: | Line 967: | ||
MsgBox(0, "FizzBuzz", $i) |
MsgBox(0, "FizzBuzz", $i) |
||
EndIf |
EndIf |
||
Next</ |
Next</syntaxhighlight> |
||
===Example2=== |
===Example2=== |
||
Output via console, logfile and/or messagebox: |
Output via console, logfile and/or messagebox: |
||
< |
<syntaxhighlight lang="autoit">#include <Constants.au3> |
||
; uncomment how you want to do the output |
; uncomment how you want to do the output |
||
Line 995: | Line 995: | ||
EndIf |
EndIf |
||
Next |
Next |
||
Out("# Done.")</ |
Out("# Done.")</syntaxhighlight> |
||
=={{header|Avail}}== |
=={{header|Avail}}== |
||
< |
<syntaxhighlight lang="avail">For each i from 1 to 100 do [ |
||
Print: |
Print: |
||
if i mod 15 = 0 then ["FizzBuzz"] |
if i mod 15 = 0 then ["FizzBuzz"] |
||
Line 1,005: | Line 1,005: | ||
else [“i”] |
else [“i”] |
||
++ "\n"; |
++ "\n"; |
||
];</ |
];</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 1,011: | Line 1,011: | ||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
< |
<syntaxhighlight lang="axe">For(I,1,100) |
||
!If I^3??I^5 |
!If I^3??I^5 |
||
Disp "FIZZBUZZ",i |
Disp "FIZZBUZZ",i |
||
Line 1,023: | Line 1,023: | ||
.Pause to allow the user to actually read the output |
.Pause to allow the user to actually read the output |
||
Pause 1000 |
Pause 1000 |
||
End</ |
End</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">main: |
||
{ { iter 1 + dup |
{ { iter 1 + dup |
||
Line 1,047: | Line 1,047: | ||
"\n" << } |
"\n" << } |
||
100 times }</ |
100 times }</syntaxhighlight> |
||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
Line 1,054: | Line 1,054: | ||
=={{header|bash}}== |
=={{header|bash}}== |
||
Any bash hacker would do this as a one liner at the shell, so... |
Any bash hacker would do this as a one liner at the shell, so... |
||
< |
<syntaxhighlight lang="bash">for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n; done</syntaxhighlight> |
||
For the sake of readability... |
For the sake of readability... |
||
< |
<syntaxhighlight lang="bash">for n in {1..100}; do |
||
((( n % 15 == 0 )) && echo 'FizzBuzz') || |
((( n % 15 == 0 )) && echo 'FizzBuzz') || |
||
((( n % 5 == 0 )) && echo 'Buzz') || |
((( n % 5 == 0 )) && echo 'Buzz') || |
||
((( n % 3 == 0 )) && echo 'Fizz') || |
((( n % 3 == 0 )) && echo 'Fizz') || |
||
echo $n; |
echo $n; |
||
done</ |
done</syntaxhighlight> |
||
Here's a very concise approach, with only 75 characters total. |
Here's a very concise approach, with only 75 characters total. |
||
Unfortunately it relies on aspects of Bash which are rarely used. |
Unfortunately it relies on aspects of Bash which are rarely used. |
||
< |
<syntaxhighlight lang="bash">for i in {1..100};do((i%3))&&x=||x=Fizz;((i%5))||x+=Buzz;echo ${x:-$i};done</syntaxhighlight> |
||
Here's the concise approach again, this time separated into multiple lines. |
Here's the concise approach again, this time separated into multiple lines. |
||
< |
<syntaxhighlight lang="bash"># FizzBuzz in Bash. A concise version, but with verbose comments. |
||
for i in {1..100} # Use i to loop from "1" to "100", inclusive. |
for i in {1..100} # Use i to loop from "1" to "100", inclusive. |
||
do ((i % 3)) && # If i is not divisible by 3... |
do ((i % 3)) && # If i is not divisible by 3... |
||
Line 1,074: | Line 1,074: | ||
x+=Buzz # ...Otherwise, append (not set) the string "Buzz" to x. |
x+=Buzz # ...Otherwise, append (not set) the string "Buzz" to x. |
||
echo ${x:-$i} # Print x unless it is blanked out. Otherwise, print i. |
echo ${x:-$i} # Print x unless it is blanked out. Otherwise, print i. |
||
done</ |
done</syntaxhighlight> |
||
It's a bit silly to optimize such a small & fast program, |
It's a bit silly to optimize such a small & fast program, |
||
but for the sake of algorithm analysis it's worth noting that |
but for the sake of algorithm analysis it's worth noting that |
||
Line 1,098: | Line 1,098: | ||
FOR /L version: |
FOR /L version: |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
for /L %%i in (1,1,100) do call :tester %%i |
for /L %%i in (1,1,100) do call :tester %%i |
||
goto :eof |
goto :eof |
||
Line 1,122: | Line 1,122: | ||
:NotFizz |
:NotFizz |
||
echo %1 |
echo %1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Loop version: |
Loop version: |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
set n=1 |
set n=1 |
||
Line 1,154: | Line 1,154: | ||
:NotFizz |
:NotFizz |
||
echo %1</ |
echo %1</syntaxhighlight> |
||
FOR /L with a block instead of very-high-overhead subroutine call: |
FOR /L with a block instead of very-high-overhead subroutine call: |
||
< |
<syntaxhighlight lang="dos">@echo off & setlocal enabledelayedexpansion |
||
for /l %%i in (1,1,100) do ( |
for /l %%i in (1,1,100) do ( |
||
set /a m5=%%i %% 5 |
set /a m5=%%i %% 5 |
||
Line 1,167: | Line 1,167: | ||
if "!s!"=="" set s=%%i |
if "!s!"=="" set s=%%i |
||
echo !s! |
echo !s! |
||
)</ |
)</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
Line 1,175: | Line 1,175: | ||
This solution never uses <tt>else</tt>, because bc has no <tt>else</tt> keyword (but some implementations add <tt>else</tt> as an extension). |
This solution never uses <tt>else</tt>, because bc has no <tt>else</tt> keyword (but some implementations add <tt>else</tt> as an extension). |
||
< |
<syntaxhighlight lang="bc">for (i = 1; i <= 100; i++) { |
||
w = 0 |
w = 0 |
||
if (i % 3 == 0) { "Fizz"; w = 1; } |
if (i % 3 == 0) { "Fizz"; w = 1; } |
||
Line 1,183: | Line 1,183: | ||
" |
" |
||
} |
} |
||
quit</ |
quit</syntaxhighlight> |
||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">GET "libhdr" |
||
LET start() BE $( |
LET start() BE $( |
||
Line 1,204: | Line 1,204: | ||
$) |
$) |
||
$) |
$) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|beeswax}}== |
=={{header|beeswax}}== |
||
Line 1,212: | Line 1,212: | ||
“Ordinary” FizzBuzz solution: |
“Ordinary” FizzBuzz solution: |
||
< |
<syntaxhighlight lang="beeswax"> > q |
||
>@F5~%"d@F{ > @F q |
>@F5~%"d@F{ > @F q |
||
_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp |
_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp |
||
;bL@~.~4~.5~5@ P<</ |
;bL@~.~4~.5~5@ P<</syntaxhighlight> |
||
Example without double mod 5 check, using a flag instead, to check if Fizz already got printed (in this case the number n must not be printed if mod 5 is > 0): |
Example without double mod 5 check, using a flag instead, to check if Fizz already got printed (in this case the number n must not be printed if mod 5 is > 0): |
||
< |
<syntaxhighlight lang="beeswax"> >@?q |
||
> q >Ag'd@{?p |
> q >Ag'd@{?p |
||
_>"1F3~%'d`Fizz`f>@F5~%'d`Buzz`@p |
_>"1F3~%'d`Fizz`f>@F5~%'d`Buzz`@p |
||
b P~;"-~@~.+0~P9@N?<</ |
b P~;"-~@~.+0~P9@N?<</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
Line 1,229: | Line 1,229: | ||
=={{header|blz}}== |
=={{header|blz}}== |
||
< |
<syntaxhighlight lang="blz">for i = 0; i <= 100; i++ |
||
out = "" |
out = "" |
||
if i % 3 == 0 |
if i % 3 == 0 |
||
Line 1,241: | Line 1,241: | ||
end |
end |
||
print(out) |
print(out) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Boo}}== |
=={{header|Boo}}== |
||
< |
<syntaxhighlight lang="boo">def fizzbuzz(size): |
||
for i in range(1, size): |
for i in range(1, size): |
||
if i%15 == 0: |
if i%15 == 0: |
||
Line 1,255: | Line 1,255: | ||
print i |
print i |
||
fizzbuzz(101)</ |
fizzbuzz(101)</syntaxhighlight> |
||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
< |
<syntaxhighlight lang="bqn">(∾´∾⟜"Fizz"‿"Buzz"/˜·(¬∨´)⊸∾0=3‿5|⊢)¨1+↕100</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">0:?i&whl'(1+!i:<101:?i&out$(mod$(!i.3):0&(mod$(!i.5):0&FizzBuzz|Fizz)|mod$(!i.5):0&Buzz|!i))</syntaxhighlight> |
||
Same code, pretty printed: |
Same code, pretty printed: |
||
< |
<syntaxhighlight lang="bracmat"> 0:?i |
||
& whl |
& whl |
||
' ( 1+!i:<101:?i |
' ( 1+!i:<101:?i |
||
Line 1,274: | Line 1,274: | ||
| !i |
| !i |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Brainf***}}== |
=={{header|Brainf***}}== |
||
Line 1,280: | Line 1,280: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">1.to 100 { n | |
||
true? n % 15 == 0 |
true? n % 15 == 0 |
||
{ p "FizzBuzz" } |
{ p "FizzBuzz" } |
||
Line 1,290: | Line 1,290: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|BrightScript (for Roku)}}== |
=={{header|BrightScript (for Roku)}}== |
||
< |
<syntaxhighlight lang="brightscript">FOR i = 1 TO 100 |
||
fz = i MOD 3 = 0 |
fz = i MOD 3 = 0 |
||
bz = i MOD 5 = 0 |
bz = i MOD 5 = 0 |
||
Line 1,305: | Line 1,305: | ||
END IF |
END IF |
||
? str |
? str |
||
END FOR</ |
END FOR</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
For 2 prime numbers and based on a similar minimal [[#JavaScript|JavaScript]] solution with low signal-to-noise, the C code is: |
For 2 prime numbers and based on a similar minimal [[#JavaScript|JavaScript]] solution with low signal-to-noise, the C code is: |
||
< |
<syntaxhighlight lang="c"> int i = 0 ; char B[88] ; |
||
while ( i++ < 100 ) |
while ( i++ < 100 ) |
||
!sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" ) |
!sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" ) |
||
? sprintf( B, "%d", i ):0, printf( ", %s", B );</ |
? sprintf( B, "%d", i ):0, printf( ", %s", B );</syntaxhighlight> |
||
With 4 prime numbers: |
With 4 prime numbers: |
||
< |
<syntaxhighlight lang="c"> int i = 0 ; char B[88] ; |
||
while ( i++ < 100 ) |
while ( i++ < 100 ) |
||
!sprintf( B, "%s%s%s%s", |
!sprintf( B, "%s%s%s%s", |
||
i%3 ? "":"Fiz", i%5 ? "":"Buz", i%7 ? "":"Goz", i%11 ? "":"Kaz" ) |
i%3 ? "":"Fiz", i%5 ? "":"Buz", i%7 ? "":"Goz", i%11 ? "":"Kaz" ) |
||
? sprintf( B, "%d", i ):0, printf( ", %s", B );</ |
? sprintf( B, "%d", i ):0, printf( ", %s", B );</syntaxhighlight> |
||
< |
<syntaxhighlight lang="c">Output: ..., 89, FizBuz, Goz, 92, Fiz, 94, Buz, Fiz, 97, Goz, FizKaz, Buz</syntaxhighlight> |
||
One line version, with pretty printing |
One line version, with pretty printing |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
int main() { |
int main() { |
||
for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n"); |
for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n"); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
This actually works (the array init part, saves 6 bytes of static data, whee):< |
This actually works (the array init part, saves 6 bytes of static data, whee):<syntaxhighlight lang="c">#include<stdio.h> |
||
int main () |
int main () |
||
Line 1,338: | Line 1,338: | ||
printf(s[!(i % 3) + 2 * !(i % 5)], i); |
printf(s[!(i % 3) + 2 * !(i % 5)], i); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="c">#include<stdio.h> |
||
int main (void) |
int main (void) |
||
Line 1,359: | Line 1,359: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Implicit int main and return 0 (C99+): |
Implicit int main and return 0 (C99+): |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
main() { |
main() { |
||
Line 1,376: | Line 1,376: | ||
i++; |
i++; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
obfuscated: |
obfuscated: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#define F(x,y) printf("%s",i%x?"":#y"zz") |
#define F(x,y) printf("%s",i%x?"":#y"zz") |
||
int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;}</ |
int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;}</syntaxhighlight> |
||
With numbers theory: < |
With numbers theory: <syntaxhighlight lang="c">#include <stdio.h> |
||
int main(void) |
int main(void) |
||
Line 1,393: | Line 1,393: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Without conditionals, anything in the loop body gcc compiles with branching, duplicate tests or duplicate strings. Depends on ASCII and two's complement arithmetic: |
Without conditionals, anything in the loop body gcc compiles with branching, duplicate tests or duplicate strings. Depends on ASCII and two's complement arithmetic: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
int main() |
int main() |
||
{ |
{ |
||
Line 1,407: | Line 1,407: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">class Program |
||
{ |
{ |
||
public void FizzBuzzGo() |
public void FizzBuzzGo() |
||
Line 1,443: | Line 1,443: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="csharp">class Program |
||
{ |
{ |
||
static void Main() |
static void Main() |
||
Line 1,462: | Line 1,462: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 1,480: | Line 1,480: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Globalization; |
using System.Globalization; |
||
using System.Linq; |
using System.Linq; |
||
Line 1,504: | Line 1,504: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace FizzBuzz |
namespace FizzBuzz |
||
{ |
{ |
||
Line 1,534: | Line 1,534: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Globalization; |
using System.Globalization; |
||
Line 1,565: | Line 1,565: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 1,579: | Line 1,579: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===With C#8 switch expressions=== |
===With C#8 switch expressions=== |
||
< |
<syntaxhighlight lang="csharp">class Program |
||
{ |
{ |
||
public static string FizzBuzzIt(int n) => |
public static string FizzBuzzIt(int n) => |
||
Line 1,601: | Line 1,601: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===TDD using delegates=== |
===TDD using delegates=== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Collections; |
using System.Collections; |
||
using System.Collections.Generic; |
using System.Collections.Generic; |
||
Line 1,687: | Line 1,687: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Good old C ways=== |
===Good old C ways=== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
int max = 100; |
int max = 100; |
||
for(int i=0; |
for(int i=0; |
||
Line 1,697: | Line 1,697: | ||
Console.WriteLine("{0}{1}{2}", i%3==0 ? "Fizz" : "", i%5==0 ? "Buzz" : "", i%3!=0 && i%5!=0 ? i.ToString() : "") |
Console.WriteLine("{0}{1}{2}", i%3==0 ? "Fizz" : "", i%5==0 ? "Buzz" : "", i%3!=0 && i%5!=0 ? i.ToString() : "") |
||
){} |
){} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
===minimal conditions=== |
===minimal conditions=== |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <chrono> |
#include <chrono> |
||
Line 1,742: | Line 1,742: | ||
</syntaxhighlight> |
</syntaxhighlight> |
||
===with modulo=== |
===with modulo=== |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
using namespace std; |
using namespace std; |
||
Line 1,761: | Line 1,761: | ||
}</syntaxhighlight> |
}</syntaxhighlight> |
||
===without modulo 15=== |
===without modulo 15=== |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
using namespace std; |
using namespace std; |
||
Line 1,782: | Line 1,782: | ||
===without modulo=== |
===without modulo=== |
||
Modulo can be expensive on some architectures. |
Modulo can be expensive on some architectures. |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
int main() |
int main() |
||
Line 1,801: | Line 1,801: | ||
===using std::transform=== |
===using std::transform=== |
||
{{works with|C++11}} |
{{works with|C++11}} |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <algorithm> |
#include <algorithm> |
||
#include <vector> |
#include <vector> |
||
Line 1,828: | Line 1,828: | ||
===metaprogramming=== |
===metaprogramming=== |
||
Version computing FizzBuzz at compile time with metaprogramming: |
Version computing FizzBuzz at compile time with metaprogramming: |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
template <int n, int m3, int m5> |
template <int n, int m3, int m5> |
||
Line 1,878: | Line 1,878: | ||
===hardcore templates=== |
===hardcore templates=== |
||
Compile with -ftemplate-depth-9000 -std=c++0x: |
Compile with -ftemplate-depth-9000 -std=c++0x: |
||
<syntaxhighlight lang=cpp>#include <iostream> |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <string> |
#include <string> |
||
#include <cstdlib> |
#include <cstdlib> |
||
Line 2,048: | Line 2,048: | ||
=={{header|Cduce}}== |
=={{header|Cduce}}== |
||
< |
<syntaxhighlight lang="ocaml">(* FizzBuzz in CDuce *) |
||
let format (n : Int) : Latin1 = |
let format (n : Int) : Latin1 = |
||
Line 2,065: | Line 2,065: | ||
let fizbuzz (size : Int) : _ = fizz (1, size);; |
let fizbuzz (size : Int) : _ = fizz (1, size);; |
||
let _ = fizbuzz(100);;</ |
let _ = fizbuzz(100);;</syntaxhighlight> |
||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() => {for (i in 1..100) {for (j->k in [3->"Fizz", 5->"Buzz"]) if (j.divides(i)) k}.reduce(plus) else i}.each(print);</syntaxhighlight> |
||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
< |
<syntaxhighlight lang="chapel">proc fizzbuzz(n) { |
||
for i in 1..n do |
for i in 1..n do |
||
if i % 15 == 0 then |
if i % 15 == 0 then |
||
Line 2,083: | Line 2,083: | ||
} |
} |
||
fizzbuzz(100);</ |
fizzbuzz(100);</syntaxhighlight> |
||
=={{header|Chef}}== |
=={{header|Chef}}== |
||
Line 2,089: | Line 2,089: | ||
=={{header|Clay}}== |
=={{header|Clay}}== |
||
< |
<syntaxhighlight lang="clay">main() { |
||
for(i in range(1,100)) { |
for(i in range(1,100)) { |
||
if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz"); |
if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz"); |
||
Line 2,096: | Line 2,096: | ||
else print(i); |
else print(i); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clipper}}== |
=={{header|Clipper}}== |
||
Also compiles with Harbour (Harbour 3.2.0dev (r1405201749)) |
Also compiles with Harbour (Harbour 3.2.0dev (r1405201749)) |
||
< |
<syntaxhighlight lang="clipper">PROCEDURE Main() |
||
LOCAL n |
LOCAL n |
||
Line 2,112: | Line 2,112: | ||
RETURN |
RETURN |
||
</syntaxhighlight> |
|||
</lang> |
|||
The advantage of this approach is that it is trivial to add another factor: |
The advantage of this approach is that it is trivial to add another factor: |
||
<pre>AEval( {{3,"Fizz"},{5,"Buzz"},{9,"Jazz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")})</pre> |
<pre>AEval( {{3,"Fizz"},{5,"Buzz"},{9,"Jazz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")})</pre> |
||
=={{header|CLIPS}}== |
=={{header|CLIPS}}== |
||
< |
<syntaxhighlight lang="clips">(deffacts count |
||
(count-to 100) |
(count-to 100) |
||
) |
) |
||
Line 2,142: | Line 2,142: | ||
(priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf) |
(priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure"> |
||
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz")))) |
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz")))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
(defn fizzbuzz [start finish] |
(defn fizzbuzz [start finish] |
||
(map (fn [n] |
(map (fn [n] |
||
Line 2,159: | Line 2,159: | ||
(range start finish))) |
(range start finish))) |
||
(fizzbuzz 1 100) |
(fizzbuzz 1 100) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="lisp">(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz" |
||
(zero? (mod x 5)) "Buzz" |
(zero? (mod x 5)) "Buzz" |
||
(zero? (mod x 3)) "Fizz" |
(zero? (mod x 3)) "Fizz" |
||
:else x)) |
:else x)) |
||
(range 1 101))</ |
(range 1 101))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(def fizzbuzz (map |
||
#(cond (zero? (mod % 15)) "FizzBuzz" |
#(cond (zero? (mod % 15)) "FizzBuzz" |
||
(zero? (mod % 5)) "Buzz" |
(zero? (mod % 5)) "Buzz" |
||
(zero? (mod % 3)) "Fizz" |
(zero? (mod % 3)) "Fizz" |
||
:else %) |
:else %) |
||
(iterate inc 1)))</ |
(iterate inc 1)))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(defn fizz-buzz |
||
([] (fizz-buzz (range 1 101))) |
([] (fizz-buzz (range 1 101))) |
||
([lst] |
([lst] |
||
Line 2,186: | Line 2,186: | ||
(buzz? n) b |
(buzz? n) b |
||
:else n)) |
:else n)) |
||
lst)] items))))</ |
lst)] items))))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="clojure">(map (fn [n] |
||
(if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") |
(if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") |
||
(when (zero? (mod n 5)) "Buzz")))] |
(when (zero? (mod n 5)) "Buzz")))] |
||
(apply str fb) |
(apply str fb) |
||
n)) |
n)) |
||
(range 1 101))</ |
(range 1 101))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="clojure">(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) ) |
||
(range) |
(range) |
||
(cycle [ "" "" "Fizz" ]) |
(cycle [ "" "" "Fizz" ]) |
||
(cycle [ "" "" "" "" "Buzz" ])))</ |
(cycle [ "" "" "" "" "Buzz" ])))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % "Fizz" "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="clojure">(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)] |
||
(take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))</ |
(take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="clojure">(take 100 |
||
(map #(if (pos? (compare %1 %2)) %1 %2) |
(map #(if (pos? (compare %1 %2)) %1 %2) |
||
(map str (drop 1 (range))) |
(map str (drop 1 (range))) |
||
(map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"])))) |
(map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"])))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
;;Using clojure maps |
;;Using clojure maps |
||
(defn fizzbuzz |
(defn fizzbuzz |
||
Line 2,225: | Line 2,225: | ||
[max] |
[max] |
||
(map fizzbuzz (range 1 (inc max)))) |
(map fizzbuzz (range 1 (inc max)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
(take 100 |
(take 100 |
||
(map #(str %1 %2 (if-not (or %1 %2) %3)) |
(map #(str %1 %2 (if-not (or %1 %2) %3)) |
||
Line 2,233: | Line 2,233: | ||
(rest (range)) |
(rest (range)) |
||
)) |
)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
(take 100 |
(take 100 |
||
( |
( |
||
Line 2,254: | Line 2,254: | ||
) ;;endfn apply |
) ;;endfn apply |
||
) ;;endtake |
) ;;endtake |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
(take 100 |
(take 100 |
||
(map-indexed |
(map-indexed |
||
Line 2,263: | Line 2,263: | ||
) |
) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
(take 100 |
(take 100 |
||
(->> |
(->> |
||
Line 2,272: | Line 2,272: | ||
) |
) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="clojure"> |
||
(take 100 |
(take 100 |
||
(map-indexed |
(map-indexed |
||
Line 2,281: | Line 2,281: | ||
) |
) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">start_up = proc () |
||
po: stream := stream$primary_output() |
po: stream := stream$primary_output() |
||
Line 2,294: | Line 2,294: | ||
stream$putl(po, out) |
stream$putl(po, out) |
||
end |
end |
||
end start_up</ |
end start_up</syntaxhighlight> |
||
=={{header|CMake}}== |
=={{header|CMake}}== |
||
< |
<syntaxhighlight lang="cmake">foreach(i RANGE 1 100) |
||
math(EXPR off3 "${i} % 3") |
math(EXPR off3 "${i} % 3") |
||
math(EXPR off5 "${i} % 5") |
math(EXPR off5 "${i} % 5") |
||
Line 2,309: | Line 2,309: | ||
message(${i}) |
message(${i}) |
||
endif() |
endif() |
||
endforeach(i)</ |
endforeach(i)</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Line 2,315: | Line 2,315: | ||
===Canonical version=== |
===Canonical version=== |
||
{{works with|OpenCOBOL}}<!-- http://www.opencobol.org/ --> |
{{works with|OpenCOBOL}}<!-- http://www.opencobol.org/ --> |
||
< |
<syntaxhighlight lang="cobol"> * FIZZBUZZ.COB |
||
* cobc -x -g FIZZBUZZ.COB |
* cobc -x -g FIZZBUZZ.COB |
||
* |
* |
||
Line 2,350: | Line 2,350: | ||
END-PERFORM |
END-PERFORM |
||
DISPLAY "" |
DISPLAY "" |
||
STOP RUN.</ |
STOP RUN.</syntaxhighlight> |
||
===Simpler version=== |
===Simpler version=== |
||
I know this doesn't have the full-bodied, piquant flavor |
I know this doesn't have the full-bodied, piquant flavor |
||
expected from COBOL, but it is a little shorter. |
expected from COBOL, but it is a little shorter. |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
< |
<syntaxhighlight lang="cobol">Identification division. |
||
Program-id. fizz-buzz. |
Program-id. fizz-buzz. |
||
Line 2,370: | Line 2,370: | ||
else display num |
else display num |
||
end-perform. |
end-perform. |
||
Stop run.</ |
Stop run.</syntaxhighlight> |
||
===Evaluate Version=== |
===Evaluate Version=== |
||
I think this shows clearly that it's resolving the problem and illuminating the rules specified |
I think this shows clearly that it's resolving the problem and illuminating the rules specified |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
< |
<syntaxhighlight lang="cobol"> |
||
IDENTIFICATION DIVISION. |
IDENTIFICATION DIVISION. |
||
PROGRAM-ID. FIZZBUZZ. |
PROGRAM-ID. FIZZBUZZ. |
||
Line 2,401: | Line 2,401: | ||
STOP RUN |
STOP RUN |
||
. |
. |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Chase the Fizz=== |
===Chase the Fizz=== |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
A solution that simply evaluates and adds. |
A solution that simply evaluates and adds. |
||
< |
<syntaxhighlight lang="cobol"> >>SOURCE FORMAT FREE |
||
identification division. |
identification division. |
||
program-id. fizzbuzz. |
program-id. fizzbuzz. |
||
Line 2,435: | Line 2,435: | ||
. |
. |
||
end program fizzbuzz. |
end program fizzbuzz. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Coco}}== |
=={{header|Coco}}== |
||
< |
<syntaxhighlight lang="coco">for i from 1 to 100 |
||
console.log do |
console.log do |
||
if i % 15 == 0 then 'FizzBuzz' |
if i % 15 == 0 then 'FizzBuzz' |
||
else if i % 3 == 0 then 'Fizz' |
else if i % 3 == 0 then 'Fizz' |
||
else if i % 5 == 0 then 'Buzz' |
else if i % 5 == 0 then 'Buzz' |
||
else i</ |
else i</syntaxhighlight> |
||
< |
<syntaxhighlight lang="coco">for i from 1 to 100 |
||
console.log(['Fizz' unless i % 3] + ['Buzz' unless i % 5] or String(i))</ |
console.log(['Fizz' unless i % 3] + ['Buzz' unless i % 5] or String(i))</syntaxhighlight> |
||
=={{header|Coconut}}== |
=={{header|Coconut}}== |
||
< |
<syntaxhighlight lang="coconut">def fizzbuzz(n): |
||
case (n % 3, n % 5): |
case (n % 3, n % 5): |
||
match (0, 0): return "FizzBuzz" |
match (0, 0): return "FizzBuzz" |
||
Line 2,455: | Line 2,455: | ||
match (_, 0): return "Buzz" |
match (_, 0): return "Buzz" |
||
else: return n |> str |
else: return n |> str |
||
range(1,101)|> map$(fizzbuzz)|> x -> '\n'.join(x)|> print</ |
range(1,101)|> map$(fizzbuzz)|> x -> '\n'.join(x)|> print</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript">for i in [1..100] |
||
if i % 15 is 0 |
if i % 15 is 0 |
||
console.log "FizzBuzz" |
console.log "FizzBuzz" |
||
Line 2,466: | Line 2,466: | ||
console.log "Buzz" |
console.log "Buzz" |
||
else |
else |
||
console.log i</ |
console.log i</syntaxhighlight> |
||
< |
<syntaxhighlight lang="coffeescript">for i in [1..100] |
||
console.log \ |
console.log \ |
||
if i % 15 is 0 |
if i % 15 is 0 |
||
Line 2,476: | Line 2,476: | ||
"Buzz" |
"Buzz" |
||
else |
else |
||
i</ |
i</syntaxhighlight> |
||
< |
<syntaxhighlight lang="coffeescript">for i in [1..100] |
||
console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)</ |
console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang="cfm"><Cfloop from="1" to="100" index="i"> |
||
<Cfif i mod 15 eq 0>FizzBuzz |
<Cfif i mod 15 eq 0>FizzBuzz |
||
<Cfelseif i mod 5 eq 0>Fizz |
<Cfelseif i mod 5 eq 0>Fizz |
||
Line 2,487: | Line 2,487: | ||
<Cfelse><Cfoutput>#i# </Cfoutput> |
<Cfelse><Cfoutput>#i# </Cfoutput> |
||
</Cfif> |
</Cfif> |
||
</Cfloop></ |
</Cfloop></syntaxhighlight> |
||
cfscript version |
cfscript version |
||
< |
<syntaxhighlight lang="cfm"><cfscript> |
||
result = ""; |
result = ""; |
||
for(i=1;i<=100;i++){ |
for(i=1;i<=100;i++){ |
||
Line 2,495: | Line 2,495: | ||
} |
} |
||
WriteOutput(result); |
WriteOutput(result); |
||
</cfscript></ |
</cfscript></syntaxhighlight> |
||
=={{header|Comal}}== |
=={{header|Comal}}== |
||
< |
<syntaxhighlight lang="comal">0010 FOR i#:=1 TO 100 DO |
||
0020 IF i# MOD 15=0 THEN |
0020 IF i# MOD 15=0 THEN |
||
0030 PRINT "FizzBuzz" |
0030 PRINT "FizzBuzz" |
||
Line 2,509: | Line 2,509: | ||
0100 ENDIF |
0100 ENDIF |
||
0110 ENDFOR i# |
0110 ENDFOR i# |
||
0120 END</ |
0120 END</syntaxhighlight> |
||
=={{header|Comefrom0x10}}== |
=={{header|Comefrom0x10}}== |
||
< |
<syntaxhighlight lang="cf0x10">fizzbuzz |
||
mod_three = 3 |
mod_three = 3 |
||
mod_five = 5 |
mod_five = 5 |
||
Line 2,536: | Line 2,536: | ||
mod_five = mod_five + 5 |
mod_five = mod_five + 5 |
||
comefrom fizzbuzz if n is 100</ |
comefrom fizzbuzz if n is 100</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Solution 1: |
Solution 1: |
||
< |
<syntaxhighlight lang="lisp">(defun fizzbuzz () |
||
(loop for x from 1 to 100 do |
(loop for x from 1 to 100 do |
||
(princ (cond ((zerop (mod x 15)) "FizzBuzz") |
(princ (cond ((zerop (mod x 15)) "FizzBuzz") |
||
Line 2,546: | Line 2,546: | ||
((zerop (mod x 5)) "Buzz") |
((zerop (mod x 5)) "Buzz") |
||
(t x))) |
(t x))) |
||
(terpri)))</ |
(terpri)))</syntaxhighlight> |
||
Solution 2: |
Solution 2: |
||
< |
<syntaxhighlight lang="lisp">(defun fizzbuzz () |
||
(loop for x from 1 to 100 do |
(loop for x from 1 to 100 do |
||
(format t "~&~{~A~}" |
(format t "~&~{~A~}" |
||
(or (append (when (zerop (mod x 3)) '("Fizz")) |
(or (append (when (zerop (mod x 3)) '("Fizz")) |
||
(when (zerop (mod x 5)) '("Buzz"))) |
(when (zerop (mod x 5)) '("Buzz"))) |
||
(list x)))))</ |
(list x)))))</syntaxhighlight> |
||
Solution 3: |
Solution 3: |
||
< |
<syntaxhighlight lang="lisp">(defun fizzbuzz () |
||
(loop for n from 1 to 100 |
(loop for n from 1 to 100 |
||
do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%" |
do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%" |
||
(mod n 3) (mod n 5) n)))</ |
(mod n 3) (mod n 5) n)))</syntaxhighlight> |
||
Solution 4: |
Solution 4: |
||
< |
<syntaxhighlight lang="lisp">(loop as n from 1 to 100 |
||
as fizz = (zerop (mod n 3)) |
as fizz = (zerop (mod n 3)) |
||
as buzz = (zerop (mod n 5)) |
as buzz = (zerop (mod n 5)) |
||
Line 2,567: | Line 2,567: | ||
(format t |
(format t |
||
"~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%" |
"~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%" |
||
fizz buzz numb n))</ |
fizz buzz numb n))</syntaxhighlight> |
||
Solution 5: |
Solution 5: |
||
< |
<syntaxhighlight lang="lisp">(format t "~{~:[~&~;~:*~:(~a~)~]~}" |
||
(loop as n from 1 to 100 |
(loop as n from 1 to 100 |
||
as f = (zerop (mod n 3)) |
as f = (zerop (mod n 3)) |
||
Line 2,576: | Line 2,576: | ||
if f collect 'fizz |
if f collect 'fizz |
||
if b collect 'buzz |
if b collect 'buzz |
||
if (not (or f b)) collect n))</ |
if (not (or f b)) collect n))</syntaxhighlight> |
||
Solution 6: |
Solution 6: |
||
< |
<syntaxhighlight lang="lisp">(format t "~{~{~:[~;Fizz~]~:[~;Buzz~]~:[~*~;~d~]~}~%~}" |
||
(loop as n from 1 to 100 |
(loop as n from 1 to 100 |
||
as f = (zerop (mod n 3)) |
as f = (zerop (mod n 3)) |
||
as b = (zerop (mod n 5)) |
as b = (zerop (mod n 5)) |
||
collect (list f b (not (or f b)) n)))</ |
collect (list f b (not (or f b)) n)))</syntaxhighlight> |
||
Solution 7: |
Solution 7: |
||
< |
<syntaxhighlight lang="lisp">(defun core (x) |
||
(mapcar |
(mapcar |
||
#'(lambda (a b) (if (equal 0 (mod x a)) b x)) |
#'(lambda (a b) (if (equal 0 (mod x a)) b x)) |
||
Line 2,600: | Line 2,600: | ||
(print (format nil "~{~a~}" (filter-core (core a)))))) |
(print (format nil "~{~a~}" (filter-core (core a)))))) |
||
(fizzbuzz 100)</ |
(fizzbuzz 100)</syntaxhighlight> |
||
First 16 lines of output: |
First 16 lines of output: |
||
<pre> |
<pre> |
||
Line 2,624: | Line 2,624: | ||
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1] |
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1] |
||
< |
<syntaxhighlight lang="lisp"> |
||
;; Project : FizzBuzz |
;; Project : FizzBuzz |
||
Line 2,645: | Line 2,645: | ||
(= (rem n multiple) 0)) |
(= (rem n multiple) 0)) |
||
(fizzbuzz 1) |
(fizzbuzz 1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,673: | Line 2,673: | ||
=={{header|Coq}}== |
=={{header|Coq}}== |
||
< |
<syntaxhighlight lang="coq"> |
||
Require Import Coq.Lists.List. |
Require Import Coq.Lists.List. |
||
(* https://coq.inria.fr/library/Coq.Lists.List.html *) |
(* https://coq.inria.fr/library/Coq.Lists.List.html *) |
||
Line 2,740: | Line 2,740: | ||
(** This shows the string. *) |
(** This shows the string. *) |
||
Eval compute in fizz_buzz. |
Eval compute in fizz_buzz. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Line 2,747: | Line 2,747: | ||
===Straightforward version=== |
===Straightforward version=== |
||
< |
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
||
var i: uint8 := 1; |
var i: uint8 := 1; |
||
Line 2,762: | Line 2,762: | ||
print_nl(); |
print_nl(); |
||
i := i + 1; |
i := i + 1; |
||
end loop;</ |
end loop;</syntaxhighlight> |
||
===No division=== |
===No division=== |
||
Line 2,781: | Line 2,781: | ||
98-byte executable.) |
98-byte executable.) |
||
< |
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
||
var i: uint8 := 100; |
var i: uint8 := 100; |
||
Line 2,823: | Line 2,823: | ||
i := i - 1; |
i := i - 1; |
||
end loop; |
end loop; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
< |
<syntaxhighlight lang="ruby">1.upto(100) do |v| |
||
p fizz_buzz(v) |
p fizz_buzz(v) |
||
end |
end |
||
Line 2,837: | Line 2,837: | ||
word += value.to_s if word.empty? |
word += value.to_s if word.empty? |
||
word |
word |
||
end</ |
end</syntaxhighlight> |
||
A more natural solution with the string building: |
A more natural solution with the string building: |
||
< |
<syntaxhighlight lang="ruby">1.upto(100) do |n| |
||
case |
case |
||
when n % 15 == 0 |
when n % 15 == 0 |
||
Line 2,852: | Line 2,852: | ||
puts n |
puts n |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|CSS}}== |
=={{header|CSS}}== |
||
Line 2,982: | Line 2,982: | ||
=={{header|Cubescript}}== |
=={{header|Cubescript}}== |
||
<lang>alias fizzbuzz [ |
<syntaxhighlight lang="text">alias fizzbuzz [ |
||
loop i 100 [ |
loop i 100 [ |
||
push i (+ $i 1) [ |
push i (+ $i 1) [ |
||
Line 2,996: | Line 2,996: | ||
] |
] |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.conv; |
||
/// With if-else. |
/// With if-else. |
||
Line 3,051: | Line 3,051: | ||
writeln; |
writeln; |
||
100.fizzBuzzSwitch2; |
100.fizzBuzzSwitch2; |
||
}</ |
}</syntaxhighlight> |
||
Alternate version calculating values at compile time: |
Alternate version calculating values at compile time: |
||
< |
<syntaxhighlight lang="d">import std; |
||
void main() |
void main() |
||
Line 3,069: | Line 3,069: | ||
r.each!writeln; |
r.each!writeln; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang="dart"> |
||
main() { |
main() { |
||
for (int i = 1; i <= 100; i++) { |
for (int i = 1; i <= 100; i++) { |
||
Line 3,083: | Line 3,083: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|dc}}== |
=={{header|dc}}== |
||
{{trans|bc}} |
{{trans|bc}} |
||
< |
<syntaxhighlight lang="dc">[[Fizz]P 1 sw]sF |
||
[[Buzz]P 1 sw]sB |
[[Buzz]P 1 sw]sB |
||
[li p sz]sN |
[li p sz]sN |
||
Line 3,102: | Line 3,102: | ||
]sL |
]sL |
||
1 si [i = 1]sz |
1 si [i = 1]sz |
||
0 0 =L [enter Loop]sz</ |
0 0 =L [enter Loop]sz</syntaxhighlight> |
||
The bc translation written in dc style. |
The bc translation written in dc style. |
||
<syntaxhighlight lang="dc"> |
|||
<lang dc> |
|||
# dc is stack based, so we use the stack instead of a variable for our |
# dc is stack based, so we use the stack instead of a variable for our |
||
# current number. |
# current number. |
||
Line 3,122: | Line 3,122: | ||
1+d # Number += 1 and put extra copy on stack |
1+d # Number += 1 and put extra copy on stack |
||
100!<L # Continue Loop if 100 >= Number (destroys copy) |
100!<L # Continue Loop if 100 >= Number (destroys copy) |
||
]dsLx # Enter Loop</ |
]dsLx # Enter Loop</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program FizzBuzz; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 3,145: | Line 3,145: | ||
Writeln(i); |
Writeln(i); |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|DeviousYarn}}== |
=={{header|DeviousYarn}}== |
||
< |
<syntaxhighlight lang="deviousyarn">each { x range(1 100) |
||
? { divisible(x 3) |
? { divisible(x 3) |
||
p:'Fizz' } |
p:'Fizz' } |
||
Line 3,156: | Line 3,156: | ||
p:x } |
p:x } |
||
o |
o |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Draco}}== |
=={{header|Draco}}== |
||
< |
<syntaxhighlight lang="draco">proc nonrec main() void: |
||
byte i; |
byte i; |
||
for i from 1 upto 100 do |
for i from 1 upto 100 do |
||
Line 3,168: | Line 3,168: | ||
fi |
fi |
||
od |
od |
||
corp</ |
corp</syntaxhighlight> |
||
=={{header|DUP}}== |
=={{header|DUP}}== |
||
Line 3,175: | Line 3,175: | ||
Output to STDOUT via single character output. |
Output to STDOUT via single character output. |
||
< |
<syntaxhighlight lang="dup">[$$3/%$[]['F,'i,'z,'z,]?\5/%$[]['B,'u,'z,'z,]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print proper output} |
||
0[$100<][1+c;!]# {loop from 1 to 100}</ |
0[$100<][1+c;!]# {loop from 1 to 100}</syntaxhighlight> |
||
Output to STDOUT, using stored strings and a separately defined string output operator: |
Output to STDOUT, using stored strings and a separately defined string output operator: |
||
< |
<syntaxhighlight lang="dup">[\[^^>][$;,1+]#%%]⇒P {define operator P: print stored string} |
||
[$$3/%$[][0$"Fizz"P]?\5/%$[][0$"Buzz"P]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print according output} |
[$$3/%$[][0$"Fizz"P]?\5/%$[][0$"Buzz"P]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print according output} |
||
0[$100<][1+c;!]# {loop from 1 to 100}</ |
0[$100<][1+c;!]# {loop from 1 to 100}</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
< |
<syntaxhighlight lang="delphi">var i : Integer; |
||
for i := 1 to 100 do begin |
for i := 1 to 100 do begin |
||
Line 3,194: | Line 3,194: | ||
PrintLn('Buzz') |
PrintLn('Buzz') |
||
else PrintLn(i); |
else PrintLn(i); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
< |
<syntaxhighlight lang="dyalect">var n = 1 |
||
while n < 20 { |
while n < 20 { |
||
Line 3,212: | Line 3,212: | ||
n = n + 1 |
n = n + 1 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,237: | Line 3,237: | ||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">for i range 1 100: |
||
if = 0 % i 15: |
if = 0 % i 15: |
||
"FizzBuzz" |
"FizzBuzz" |
||
Line 3,246: | Line 3,246: | ||
else: |
else: |
||
i |
i |
||
!print</ |
!print</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">for i in 1..100 { |
||
println(switch ([i % 3, i % 5]) { |
println(switch ([i % 3, i % 5]) { |
||
match [==0, ==0] { "FizzBuzz" } |
match [==0, ==0] { "FizzBuzz" } |
||
Line 3,256: | Line 3,256: | ||
match _ { i } |
match _ { i } |
||
}) |
}) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
=={{header|EasyLang}}== |
||
<lang>for i = 1 to 100 |
<syntaxhighlight lang="text">for i = 1 to 100 |
||
if i mod 15 = 0 |
if i mod 15 = 0 |
||
print "FizzBuzz" |
print "FizzBuzz" |
||
Line 3,269: | Line 3,269: | ||
print i |
print i |
||
. |
. |
||
.</ |
.</syntaxhighlight> |
||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
< |
<syntaxhighlight lang="ecl">DataRec := RECORD |
||
STRING s; |
STRING s; |
||
END; |
END; |
||
Line 3,288: | Line 3,288: | ||
d := DATASET(100,MakeDataRec(COUNTER)); |
d := DATASET(100,MakeDataRec(COUNTER)); |
||
OUTPUT(d);</ |
OUTPUT(d);</syntaxhighlight> |
||
=={{header|Eero}}== |
=={{header|Eero}}== |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
int main() |
int main() |
||
Line 3,304: | Line 3,304: | ||
Log( '(%d) %@', i, s ) |
Log( '(%d) %@', i, s ) |
||
return 0</ |
return 0</syntaxhighlight> |
||
=={{header|Egel}}== |
=={{header|Egel}}== |
||
<syntaxhighlight lang="egel"> |
|||
<lang Egel> |
|||
import "prelude.eg" |
import "prelude.eg" |
||
import "io.ego" |
import "io.ego" |
||
Line 3,327: | Line 3,327: | ||
def main = fizzbuzz 1 |
def main = fizzbuzz 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
<syntaxhighlight lang="eiffel"> |
|||
<lang Eiffel> |
|||
class |
class |
||
APPLICATION |
APPLICATION |
||
Line 3,365: | Line 3,365: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ela}}== |
=={{header|Ela}}== |
||
< |
<syntaxhighlight lang="ela">open list |
||
prt x | x % 15 == 0 = "FizzBuzz" |
prt x | x % 15 == 0 = "FizzBuzz" |
||
Line 3,375: | Line 3,375: | ||
| else = x |
| else = x |
||
[1..100] |> map prt</ |
[1..100] |> map prt</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
===Standard approaches=== |
===Standard approaches=== |
||
used case |
used case |
||
< |
<syntaxhighlight lang="elixir">Enum.each 1..100, fn x -> |
||
IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do |
IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do |
||
{ true, true } -> "FizzBuzz" |
{ true, true } -> "FizzBuzz" |
||
Line 3,387: | Line 3,387: | ||
{ false, false } -> x |
{ false, false } -> x |
||
end) |
end) |
||
end</ |
end</syntaxhighlight> |
||
Alternate approach using pipes and cond: |
Alternate approach using pipes and cond: |
||
< |
<syntaxhighlight lang="elixir">#!/usr/bin/env elixir |
||
1..100 |> Enum.map(fn i -> |
1..100 |> Enum.map(fn i -> |
||
cond do |
cond do |
||
Line 3,399: | Line 3,399: | ||
true -> i |
true -> i |
||
end |
end |
||
end) |> Enum.each(fn i -> IO.puts i end)</ |
end) |> Enum.each(fn i -> IO.puts i end)</syntaxhighlight> |
||
used Stream.cycle version: |
used Stream.cycle version: |
||
< |
<syntaxhighlight lang="elixir">defmodule RC do |
||
def fizzbuzz(limit \\ 100) do |
def fizzbuzz(limit \\ 100) do |
||
fizz = Stream.cycle(["", "", "Fizz"]) |
fizz = Stream.cycle(["", "", "Fizz"]) |
||
Line 3,415: | Line 3,415: | ||
end |
end |
||
RC.fizzbuzz</ |
RC.fizzbuzz</syntaxhighlight> |
||
Yet another approach: |
Yet another approach: |
||
< |
<syntaxhighlight lang="elixir">defmodule FizzBuzz do |
||
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz" |
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz" |
||
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz" |
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz" |
||
Line 3,425: | Line 3,425: | ||
end |
end |
||
Enum.each(1..100, &IO.puts FizzBuzz.fizzbuzz &1)</ |
Enum.each(1..100, &IO.puts FizzBuzz.fizzbuzz &1)</syntaxhighlight> |
||
used anonymous function |
used anonymous function |
||
< |
<syntaxhighlight lang="elixir">f = fn(n) when rem(n,15)==0 -> "FizzBuzz" |
||
(n) when rem(n,5)==0 -> "Fizz" |
(n) when rem(n,5)==0 -> "Fizz" |
||
(n) when rem(n,3)==0 -> "Buzz" |
(n) when rem(n,3)==0 -> "Buzz" |
||
Line 3,434: | Line 3,434: | ||
end |
end |
||
for n <- 1..100, do: IO.puts f.(n)</ |
for n <- 1..100, do: IO.puts f.(n)</syntaxhighlight> |
||
Enum.at version: Returns nil if index is out of bounds. |
Enum.at version: Returns nil if index is out of bounds. |
||
< |
<syntaxhighlight lang="elixir">Enum.each(1..100, fn i -> |
||
str = "#{Enum.at([:Fizz], rem(i,3))}#{Enum.at([:Buzz], rem(i,5))}" |
str = "#{Enum.at([:Fizz], rem(i,3))}#{Enum.at([:Buzz], rem(i,5))}" |
||
IO.puts if str=="", do: i, else: str |
IO.puts if str=="", do: i, else: str |
||
end)</ |
end)</syntaxhighlight> |
||
===A macro too far=== |
===A macro too far=== |
||
The Stream.cycle version above, but as an overpowered FizzBuzz DSL. |
The Stream.cycle version above, but as an overpowered FizzBuzz DSL. |
||
< |
<syntaxhighlight lang="elixir">defmodule BadFizz do |
||
# Hand-rolls a bunch of AST before injecting the resulting FizzBuzz code. |
# Hand-rolls a bunch of AST before injecting the resulting FizzBuzz code. |
||
defmacrop automate_fizz(fizzers, n) do |
defmacrop automate_fizz(fizzers, n) do |
||
Line 3,534: | Line 3,534: | ||
end |
end |
||
BadFizz.fizz(100) # => Prints to stdout</ |
BadFizz.fizz(100) # => Prints to stdout</syntaxhighlight> |
||
=={{header|Elm}}== |
=={{header|Elm}}== |
||
A bit too simple: |
A bit too simple: |
||
< |
<syntaxhighlight lang="elm">import Html exposing (text) |
||
import List exposing (map) |
import List exposing (map) |
||
Line 3,552: | Line 3,552: | ||
"Buzz" |
"Buzz" |
||
else |
else |
||
String.fromInt num</ |
String.fromInt num</syntaxhighlight> |
||
A bit too clever: |
A bit too clever: |
||
< |
<syntaxhighlight lang="elm">import Html exposing (text) |
||
import List exposing (map) |
import List exposing (map) |
||
import String exposing (join, fromInt) |
import String exposing (join, fromInt) |
||
Line 3,572: | Line 3,572: | ||
fromInt num |
fromInt num |
||
else |
else |
||
fizz ++ buzz</ |
fizz ++ buzz</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun fizzbuzz (n) |
||
(cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz") |
(cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz") |
||
((zerop (% n 3)) "Fizz") |
((zerop (% n 3)) "Fizz") |
||
Line 3,583: | Line 3,583: | ||
;; loop & print from 0 to 100 |
;; loop & print from 0 to 100 |
||
(dotimes (i 101) |
(dotimes (i 101) |
||
(message "%s" (fizzbuzz i)))</ |
(message "%s" (fizzbuzz i)))</syntaxhighlight> |
||
=={{header|Emojicode}}== |
=={{header|Emojicode}}== |
||
===Simple 1=== |
===Simple 1=== |
||
< |
<syntaxhighlight lang="emojicode">🏁🍇 |
||
🔂 i 🆕⏩ 1 101 1 ❗ 🍇 |
🔂 i 🆕⏩ 1 101 1 ❗ 🍇 |
||
↪️ i 🚮 15 🙌 0 🍇 |
↪️ i 🚮 15 🙌 0 🍇 |
||
Line 3,601: | Line 3,601: | ||
🍉 |
🍉 |
||
🍉 |
🍉 |
||
🍉</ |
🍉</syntaxhighlight> |
||
===Simple 2=== |
===Simple 2=== |
||
< |
<syntaxhighlight lang="emojicode">🏁🍇 |
||
🔂 i 🆕⏩ 1 101 1 ❗ 🍇 |
🔂 i 🆕⏩ 1 101 1 ❗ 🍇 |
||
🔤🔤 ➡️ 🖍🆕 msg |
🔤🔤 ➡️ 🖍🆕 msg |
||
Line 3,618: | Line 3,618: | ||
🍉 |
🍉 |
||
🍉 |
🍉 |
||
🍉</ |
🍉</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">-spec fizzbuzz() -> Result :: string(). |
||
fizzbuzz() -> |
fizzbuzz() -> |
||
F = fun(N) when N rem 15 == 0 -> "FizzBuzz"; |
F = fun(N) when N rem 15 == 0 -> "FizzBuzz"; |
||
Line 3,628: | Line 3,628: | ||
(N) -> integer_to_list(N) |
(N) -> integer_to_list(N) |
||
end, |
end, |
||
lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).</ |
lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).</syntaxhighlight> |
||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM FIZZ_BUZZ |
PROGRAM FIZZ_BUZZ |
||
! |
! |
||
Line 3,649: | Line 3,649: | ||
END FOR |
END FOR |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
{{works with|Euphoria|4.0.0}} |
{{works with|Euphoria|4.0.0}} |
||
This is based on the [[VBScript]] example. |
This is based on the [[VBScript]] example. |
||
< |
<syntaxhighlight lang="euphoria">include std/utils.e |
||
function fb( atom n ) |
function fb( atom n ) |
||
Line 3,686: | Line 3,686: | ||
end for |
end for |
||
puts( 1, "\n" )</ |
puts( 1, "\n" )</syntaxhighlight> |
||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let fizzbuzz n = |
||
match n%3 = 0, n%5 = 0 with |
match n%3 = 0, n%5 = 0 with |
||
| true, false -> "fizz" |
| true, false -> "fizz" |
||
Line 3,697: | Line 3,697: | ||
let printFizzbuzz() = |
let printFizzbuzz() = |
||
[1..100] |> List.iter (fizzbuzz >> printfn "%s")</ |
[1..100] |> List.iter (fizzbuzz >> printfn "%s")</syntaxhighlight> |
||
< |
<syntaxhighlight lang="fsharp">[1..100] |
||
|> List.map (fun x -> |
|> List.map (fun x -> |
||
match x with |
match x with |
||
Line 3,705: | Line 3,705: | ||
| _ when x % 3 = 0 -> "fizz" |
| _ when x % 3 = 0 -> "fizz" |
||
| _ -> x.ToString()) |
| _ -> x.ToString()) |
||
|> List.iter (fun x -> printfn "%s" x) </ |
|> List.iter (fun x -> printfn "%s" x) </syntaxhighlight> |
||
Another example using (unnecessary) partial active pattern :D |
Another example using (unnecessary) partial active pattern :D |
||
< |
<syntaxhighlight lang="fsharp">let (|MultipleOf|_|) divisors number = |
||
if Seq.exists ((%) number >> (<>) 0) divisors |
if Seq.exists ((%) number >> (<>) 0) divisors |
||
then None |
then None |
||
Line 3,719: | Line 3,719: | ||
{ 1 .. 100 } |
{ 1 .. 100 } |
||
|> Seq.iter (fizzbuzz >> printfn "%s")</ |
|> Seq.iter (fizzbuzz >> printfn "%s")</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: math kernel io math.functions math.parser math.ranges ; |
||
IN: fizzbuzz |
IN: fizzbuzz |
||
: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ; |
: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ; |
||
Line 3,728: | Line 3,728: | ||
: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ; |
: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ; |
||
: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ; |
: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ; |
||
MAIN: main</ |
MAIN: main</syntaxhighlight> |
||
More flexible variant without divisibility tests. |
More flexible variant without divisibility tests. |
||
< |
<syntaxhighlight lang="factor"> |
||
USING: kernel sequences arrays generalizations fry math math.parser prettyprint ; |
USING: kernel sequences arrays generalizations fry math math.parser prettyprint ; |
||
IN: fizzbuzz |
IN: fizzbuzz |
||
Line 3,751: | Line 3,751: | ||
MAIN: FizzBuzzQuxx-100 |
MAIN: FizzBuzzQuxx-100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
< |
<syntaxhighlight lang="falcon">for i in [1:101] |
||
switch i % 15 |
switch i % 15 |
||
case 0 : > "FizzBuzz" |
case 0 : > "FizzBuzz" |
||
Line 3,761: | Line 3,761: | ||
default : > i |
default : > i |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
Line 3,767: | Line 3,767: | ||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom">class FizzBuzz |
||
{ |
{ |
||
public static Void main () |
public static Void main () |
||
Line 3,783: | Line 3,783: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|FBSL}}== |
=={{header|FBSL}}== |
||
'''No 'MOD 15' needed.''' |
'''No 'MOD 15' needed.''' |
||
< |
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE |
||
DIM numbers AS STRING |
DIM numbers AS STRING |
||
Line 3,803: | Line 3,803: | ||
NEXT |
NEXT |
||
PAUSE</ |
PAUSE</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fiz |
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fiz |
||
Line 3,814: | Line 3,814: | ||
=={{header|Fennel}}== |
=={{header|Fennel}}== |
||
< |
<syntaxhighlight lang="fennel">(for [i 1 100] |
||
(print (if (= (% i 15) 0) :FizzBuzz |
(print (if (= (% i 15) 0) :FizzBuzz |
||
(= (% i 3) 0) :Fizz |
(= (% i 3) 0) :Fizz |
||
(= (% i 5) 0) :Buzz |
(= (% i 5) 0) :Buzz |
||
i)))</ |
i)))</syntaxhighlight> |
||
Use pattern matching and recursive function: |
Use pattern matching and recursive function: |
||
< |
<syntaxhighlight lang="fennel">(fn fizz-buzz [from to] |
||
(print (match [(% from 3) (% from 5)] |
(print (match [(% from 3) (% from 5)] |
||
[0 0] :FizzBuzz |
[0 0] :FizzBuzz |
||
Line 3,829: | Line 3,829: | ||
(fizz-buzz (+ from 1) to))) |
(fizz-buzz (+ from 1) to))) |
||
(fizz-buzz 1 100)</ |
(fizz-buzz 1 100)</syntaxhighlight> |
||
Alternative matching pattern:{{trans|D}} |
Alternative matching pattern:{{trans|D}} |
||
< |
<syntaxhighlight lang="fennel">(for [i 1 100] |
||
(print (match (% i 15) |
(print (match (% i 15) |
||
0 :FizzBuzz |
0 :FizzBuzz |
||
(where (or 3 6 9 12)) :Fizz |
(where (or 3 6 9 12)) :Fizz |
||
(where (or 5 10) :Buzz |
(where (or 5 10) :Buzz |
||
_ i)))</ |
_ i)))</syntaxhighlight> |
||
=={{header|FOCAL}}== |
=={{header|FOCAL}}== |
||
<tt>FITR</tt> is a built-in function that truncates a floating-point number to an integer. Note that FOCAL uses an arithmetic (three-way) <tt>IF</tt> statement, rather like early Fortran. |
<tt>FITR</tt> is a built-in function that truncates a floating-point number to an integer. Note that FOCAL uses an arithmetic (three-way) <tt>IF</tt> statement, rather like early Fortran. |
||
< |
<syntaxhighlight lang="focal">01.10 FOR I=1,100; DO 2.0 |
||
01.20 QUIT |
01.20 QUIT |
||
Line 3,855: | Line 3,855: | ||
02.90 TYPE "Buzz" ! |
02.90 TYPE "Buzz" ! |
||
02.95 RETURN |
02.95 RETURN |
||
02.99 TYPE %3, I, !</ |
02.99 TYPE %3, I, !</syntaxhighlight> |
||
=={{header|Fermat}}== |
=={{header|Fermat}}== |
||
< |
<syntaxhighlight lang="fermat"> |
||
for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od</ |
for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
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</pre> |
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</pre> |
||
Line 3,865: | Line 3,865: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
===table-driven=== |
===table-driven=== |
||
< |
<syntaxhighlight lang="forth">: fizz ( n -- ) drop ." Fizz" ; |
||
: buzz ( n -- ) drop ." Buzz" ; |
: buzz ( n -- ) drop ." Buzz" ; |
||
: fb ( n -- ) drop ." FizzBuzz" ; |
: fb ( n -- ) drop ." FizzBuzz" ; |
||
Line 3,875: | Line 3,875: | ||
' fizz , ' . , ' . , |
' fizz , ' . , ' . , |
||
' fizz , ' buzz , ' . , |
' fizz , ' buzz , ' . , |
||
' fizz , ' . , ' . ,</ |
' fizz , ' . , ' . ,</syntaxhighlight> |
||
===or the classic approach=== |
===or the classic approach=== |
||
< |
<syntaxhighlight lang="forth">: .fizzbuzz ( n -- ) |
||
0 pad c! |
0 pad c! |
||
dup 3 mod 0= if s" Fizz" pad place then |
dup 3 mod 0= if s" Fizz" pad place then |
||
Line 3,885: | Line 3,885: | ||
: zz ( n -- ) |
: zz ( n -- ) |
||
1+ 1 do i .fizzbuzz cr loop ; |
1+ 1 do i .fizzbuzz cr loop ; |
||
100 zz</ |
100 zz</syntaxhighlight> |
||
===the well factored approach=== |
===the well factored approach=== |
||
SYNONYM is a Forth200x word. |
SYNONYM is a Forth200x word. |
||
< |
<syntaxhighlight lang="forth">SYNONYM NOT INVERT \ Bitwise boolean not |
||
: Fizz? ( n -- ? ) 3 MOD 0= DUP IF ." Fizz" THEN ; |
: Fizz? ( n -- ? ) 3 MOD 0= DUP IF ." Fizz" THEN ; |
||
Line 3,897: | Line 3,897: | ||
101 1 DO CR I DUP Fizz? OVER Buzz? OR NOT ?print LOOP ; |
101 1 DO CR I DUP Fizz? OVER Buzz? OR NOT ?print LOOP ; |
||
FizzBuzz</ |
FizzBuzz</syntaxhighlight> |
||
===the unrolled approach=== |
===the unrolled approach=== |
||
< |
<syntaxhighlight lang="forth">: n ( n -- n+1 ) dup . 1+ ; |
||
: f ( n -- n+1 ) ." Fizz " 1+ ; |
: f ( n -- n+1 ) ." Fizz " 1+ ; |
||
: b ( n -- n+1 ) ." Buzz " 1+ ; |
: b ( n -- n+1 ) ." Buzz " 1+ ; |
||
Line 3,906: | Line 3,906: | ||
: fb15 ( n -- n+15 ) fb10 n f n n fb ; |
: fb15 ( n -- n+15 ) fb10 n f n n fb ; |
||
: fb100 ( n -- n+100 ) fb15 fb15 fb15 fb15 fb15 fb15 fb10 ; |
: fb100 ( n -- n+100 ) fb15 fb15 fb15 fb15 fb15 fb15 fb10 ; |
||
: .fizzbuzz ( -- ) 1 fb100 drop ;</ |
: .fizzbuzz ( -- ) 1 fb100 drop ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
In ANSI FORTRAN 77 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features): |
In ANSI FORTRAN 77 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features): |
||
< |
<syntaxhighlight lang="fortran">program fizzbuzz_if |
||
integer :: i |
integer :: i |
||
Line 3,920: | Line 3,920: | ||
end if |
end if |
||
end do |
end do |
||
end program fizzbuzz_if</ |
end program fizzbuzz_if</syntaxhighlight> |
||
This example uses If statements to print "Fizz" and "Buzz" next to each other if the number is divisible by 3 and 5 by waiting to use a line break until after the If statements. |
This example uses If statements to print "Fizz" and "Buzz" next to each other if the number is divisible by 3 and 5 by waiting to use a line break until after the If statements. |
||
< |
<syntaxhighlight lang="fortran">program FizzBuzz |
||
implicit none |
implicit none |
||
integer :: i = 1 |
integer :: i = 1 |
||
Line 3,933: | Line 3,933: | ||
end do |
end do |
||
end program FizzBuzz |
end program FizzBuzz |
||
</syntaxhighlight> |
|||
</lang> |
|||
In ISO Fortran 90 or later use SELECT-CASE statement: |
In ISO Fortran 90 or later use SELECT-CASE statement: |
||
< |
<syntaxhighlight lang="fortran">program fizzbuzz_select |
||
integer :: i |
integer :: i |
||
Line 3,946: | Line 3,946: | ||
end select |
end select |
||
end do |
end do |
||
end program fizzbuzz_select</ |
end program fizzbuzz_select</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Line 3,952: | Line 3,952: | ||
=={{header|Frege}}== |
=={{header|Frege}}== |
||
< |
<syntaxhighlight lang="frege">gen n word = cycle (take (n - 1) (repeat "") ++ [word]) |
||
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz") |
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz") |
||
fizzbuzz = zipWith combine pattern [1..] where |
fizzbuzz = zipWith combine pattern [1..] where |
||
Line 3,958: | Line 3,958: | ||
then show number |
then show number |
||
else word |
else word |
||
show $ take 100 fizzbuzz</ |
show $ take 100 fizzbuzz</syntaxhighlight> |
||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink">for i = 1 to 100 |
||
{ |
{ |
||
flag = false |
flag = false |
||
Line 3,980: | Line 3,980: | ||
println[] |
println[] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic">include "NSLog.incl" |
||
long fizz, buzz, i |
long fizz, buzz, i |
||
Line 3,996: | Line 3,996: | ||
next i |
next i |
||
HandleEvents</ |
HandleEvents</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,112: | Line 4,112: | ||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=efbe83377a1eabe475d8eba13965cfde Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=efbe83377a1eabe475d8eba13965cfde Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim siCount As Short |
Dim siCount As Short |
||
Dim sText As String |
Dim sText As String |
||
Line 4,124: | Line 4,124: | ||
Next |
Next |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,230: | Line 4,230: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">FizzBuzz := function() |
||
local i; |
local i; |
||
for i in [1 .. 100] do |
for i in [1 .. 100] do |
||
Line 4,243: | Line 4,243: | ||
fi; |
fi; |
||
od; |
od; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Genyris}}== |
=={{header|Genyris}}== |
||
<syntaxhighlight lang="genyris"> |
|||
<lang Genyris> |
|||
@prefix u "http://www.genyris.org/lang/utilities#" |
@prefix u "http://www.genyris.org/lang/utilities#" |
||
Line 4,268: | Line 4,268: | ||
fb |
fb |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|GFA Basic}}== |
=={{header|GFA Basic}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
' Fizz Buzz |
' Fizz Buzz |
||
' |
' |
||
Line 4,286: | Line 4,286: | ||
ENDIF |
ENDIF |
||
NEXT i% |
NEXT i% |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Gleam}}== |
=={{header|Gleam}}== |
||
<lang>import gleam/int |
<syntaxhighlight lang="text">import gleam/int |
||
import gleam/io |
import gleam/io |
||
import gleam/iterator |
import gleam/iterator |
||
Line 4,308: | Line 4,308: | ||
_, _ -> int.to_string(n) |
_, _ -> int.to_string(n) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
===switch/case approach=== |
===switch/case approach=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 4,329: | Line 4,329: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===map approach=== |
===map approach=== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 4,341: | Line 4,341: | ||
}[i%5 == 0][i%3 == 0]) |
}[i%5 == 0][i%3 == 0]) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Golfscript}}== |
=={{header|Golfscript}}== |
||
< |
<syntaxhighlight lang="golfscript">100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*</syntaxhighlight> |
||
=={{header|Golo}}== |
=={{header|Golo}}== |
||
< |
<syntaxhighlight lang="golo">module FizzBuzz |
||
augment java.lang.Integer { |
augment java.lang.Integer { |
||
Line 4,363: | Line 4,363: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Gosu}}== |
=={{header|Gosu}}== |
||
< |
<syntaxhighlight lang="gosu">for (i in 1..100) { |
||
if (i % 3 == 0 && i % 5 == 0) { |
if (i % 3 == 0 && i % 5 == 0) { |
||
Line 4,386: | Line 4,386: | ||
print(i) |
print(i) |
||
}</ |
}</syntaxhighlight> |
||
One liner version (I added new lines to better readability but when you omit them it's one liner): |
One liner version (I added new lines to better readability but when you omit them it's one liner): |
||
< |
<syntaxhighlight lang="gosu">// note that compiler reports error (I don't know why) but still it's working |
||
for (i in 1..100) { |
for (i in 1..100) { |
||
print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i) |
print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }</syntaxhighlight> |
||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
Line 4,400: | Line 4,400: | ||
=={{header|Hare}}== |
=={{header|Hare}}== |
||
< |
<syntaxhighlight lang="hare"> |
||
use fmt; |
use fmt; |
||
Line 4,413: | Line 4,413: | ||
}; |
}; |
||
}; |
}; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Variant directly implementing the specification: |
Variant directly implementing the specification: |
||
< |
<syntaxhighlight lang="haskell">fizzbuzz :: Int -> String |
||
fizzbuzz x |
fizzbuzz x |
||
| f 15 = "FizzBuzz" |
| f 15 = "FizzBuzz" |
||
Line 4,427: | Line 4,427: | ||
main :: IO () |
main :: IO () |
||
main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]</ |
main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]</syntaxhighlight> |
||
< |
<syntaxhighlight lang="haskell">fizzbuzz :: Int -> String |
||
fizzbuzz n = |
fizzbuzz n = |
||
'\n' : |
'\n' : |
||
Line 4,446: | Line 4,446: | ||
main :: IO () |
main :: IO () |
||
main = putStr $ concatMap fizzbuzz [1 .. 100]</ |
main = putStr $ concatMap fizzbuzz [1 .. 100]</syntaxhighlight> |
||
Does not perform the mod 15 step, extesible to arbitrary addtional tests, ex: [bar| n `mod` 7 == 0]. |
Does not perform the mod 15 step, extesible to arbitrary addtional tests, ex: [bar| n `mod` 7 == 0]. |
||
< |
<syntaxhighlight lang="haskell">main = mapM_ (putStrLn . fizzbuzz) [1..100] |
||
fizzbuzz n = |
fizzbuzz n = |
||
Line 4,461: | Line 4,461: | ||
fizz = "Fizz" |
fizz = "Fizz" |
||
buzz = "Buzz"</ |
buzz = "Buzz"</syntaxhighlight> |
||
Alternate implementation using lazy infinite lists and avoiding use of "mod": |
Alternate implementation using lazy infinite lists and avoiding use of "mod": |
||
< |
<syntaxhighlight lang="haskell">main = mapM_ putStrLn $ take 100 $ zipWith show_number_or_fizzbuzz [1..] fizz_buzz_list |
||
show_number_or_fizzbuzz x y = if null y then show x else y |
show_number_or_fizzbuzz x y = if null y then show x else y |
||
fizz_buzz_list = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"])</ |
fizz_buzz_list = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"])</syntaxhighlight> |
||
Or in terms (still without '''mod''' or '''rem''') of a single '''zipWith3''': |
Or in terms (still without '''mod''' or '''rem''') of a single '''zipWith3''': |
||
< |
<syntaxhighlight lang="haskell">import Data.List (zipWith3) |
||
import Data.Bool (bool) |
import Data.Bool (bool) |
||
Line 4,484: | Line 4,484: | ||
main :: IO () |
main :: IO () |
||
main = mapM_ putStrLn $ take 100 fizzBuzz</ |
main = mapM_ putStrLn $ take 100 fizzBuzz</syntaxhighlight> |
||
or using an applicative test: |
or using an applicative test: |
||
< |
<syntaxhighlight lang="haskell">import Data.Bool (bool) |
||
fizzBuzz :: [String] |
fizzBuzz :: [String] |
||
Line 4,500: | Line 4,500: | ||
main :: IO () |
main :: IO () |
||
main = mapM_ putStrLn $ take 100 fizzBuzz |
main = mapM_ putStrLn $ take 100 fizzBuzz |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using heavy artillery (needs the mtl package): |
Using heavy artillery (needs the mtl package): |
||
< |
<syntaxhighlight lang="haskell"> |
||
import Control.Monad.State |
import Control.Monad.State |
||
import Control.Monad.Trans |
import Control.Monad.Trans |
||
Line 4,515: | Line 4,515: | ||
when (x `mod` 5 == 0) $ tell "Buzz" >> put False |
when (x `mod` 5 == 0) $ tell "Buzz" >> put False |
||
get >>= (flip when $ tell $ show x) |
get >>= (flip when $ tell $ show x) |
||
tell "\n"</ |
tell "\n"</syntaxhighlight> |
||
Using guards plus where. |
Using guards plus where. |
||
< |
<syntaxhighlight lang="haskell">fizzBuzz :: (Integral a) => a -> String |
||
fizzBuzz i |
fizzBuzz i |
||
| fizz && buzz = "FizzBuzz" |
| fizz && buzz = "FizzBuzz" |
||
Line 4,526: | Line 4,526: | ||
buzz = i `mod` 5 == 0 |
buzz = i `mod` 5 == 0 |
||
main = mapM_ (putStrLn . fizzBuzz) [1..100]</ |
main = mapM_ (putStrLn . fizzBuzz) [1..100]</syntaxhighlight> |
||
An elegant solution exploiting monoidal and applicative properties of functions: |
An elegant solution exploiting monoidal and applicative properties of functions: |
||
< |
<syntaxhighlight lang="haskell">import Data.Monoid |
||
fizzbuzz = max |
fizzbuzz = max |
||
Line 4,540: | Line 4,540: | ||
divisibleBy n x = x `mod` n == 0 |
divisibleBy n x = x `mod` n == 0 |
||
main = mapM_ (putStrLn . fizzbuzz) [1..100]</ |
main = mapM_ (putStrLn . fizzbuzz) [1..100]</syntaxhighlight> |
||
And pattern matching approach: |
And pattern matching approach: |
||
< |
<syntaxhighlight lang="haskell">fizzbuzz n = case (rem n 3, rem n 5) of |
||
(0, 0) -> "FizzBuzz" |
(0, 0) -> "FizzBuzz" |
||
(0, _) -> "Fizz" |
(0, _) -> "Fizz" |
||
Line 4,549: | Line 4,549: | ||
(_, _) -> show n |
(_, _) -> show n |
||
main = mapM_ (putStrLn . fizzbuzz) [1..100]</ |
main = mapM_ (putStrLn . fizzbuzz) [1..100]</syntaxhighlight> |
||
Generalised solution: |
Generalised solution: |
||
< |
<syntaxhighlight lang="haskell">wordthing :: [(Int, String)] -> Int -> String |
||
wordthing lst n = |
wordthing lst n = |
||
if matches == [] then |
if matches == [] then |
||
Line 4,564: | Line 4,564: | ||
main = do |
main = do |
||
mapM_ (putStrLn . fizzbuzz) [1..100]</ |
mapM_ (putStrLn . fizzbuzz) [1..100]</syntaxhighlight> |
||
=={{header|hexiscript}}== |
=={{header|hexiscript}}== |
||
< |
<syntaxhighlight lang="hexiscript">for let i 1; i <= 100; i++ |
||
if i % 3 = 0 && i % 5 = 0; println "FizzBuzz" |
if i % 3 = 0 && i % 5 = 0; println "FizzBuzz" |
||
elif i % 3 = 0; println "Fizz" |
elif i % 3 = 0; println "Fizz" |
||
elif i % 5 = 0; println "Buzz" |
elif i % 5 = 0; println "Buzz" |
||
else println i; endif |
else println i; endif |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">DO i = 1, 100 |
||
IF( MOD(i, 15) == 0 ) THEN |
IF( MOD(i, 15) == 0 ) THEN |
||
WRITE() "FizzBuzz" |
WRITE() "FizzBuzz" |
||
Line 4,585: | Line 4,585: | ||
WRITE() i |
WRITE() i |
||
ENDIF |
ENDIF |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
Alternatively: |
Alternatively: |
||
< |
<syntaxhighlight lang="hicest">CHARACTER string*8 |
||
DO i = 1, 100 |
DO i = 1, 100 |
||
Line 4,595: | Line 4,595: | ||
IF( string == " ") WRITE(Text=string) i |
IF( string == " ") WRITE(Text=string) i |
||
WRITE() string |
WRITE() string |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|HolyC}}== |
=={{header|HolyC}}== |
||
< |
<syntaxhighlight lang="holyc">U8 i; |
||
for (i = 1; i <= 100; i++) { |
for (i = 1; i <= 100; i++) { |
||
if (!(i % 15)) |
if (!(i % 15)) |
||
Line 4,609: | Line 4,609: | ||
Print("%d", i); |
Print("%d", i); |
||
Print("\n"); |
Print("\n"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Hoon}}== |
=={{header|Hoon}}== |
||
< |
<syntaxhighlight lang="hoon">:- %say |
||
|= [^ ~ ~] |
|= [^ ~ ~] |
||
:- %noun |
:- %noun |
||
Line 4,622: | Line 4,622: | ||
[& |] "Fizz" |
[& |] "Fizz" |
||
[| &] "Buzz" |
[| &] "Buzz" |
||
==</ |
==</syntaxhighlight> |
||
=={{header|Huginn}}== |
=={{header|Huginn}}== |
||
< |
<syntaxhighlight lang="huginn">import Algorithms as algo; |
||
main( argv_ ) { |
main( argv_ ) { |
||
Line 4,647: | Line 4,647: | ||
} |
} |
||
return ( 0 ); |
return ( 0 ); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Hy}}== |
=={{header|Hy}}== |
||
< |
<syntaxhighlight lang="lisp">(for [i (range 1 101)] (print (cond |
||
[(not (% i 15)) "FizzBuzz"] |
[(not (% i 15)) "FizzBuzz"] |
||
[(not (% i 5)) "Buzz"] |
[(not (% i 5)) "Buzz"] |
||
[(not (% i 3)) "Fizz"] |
[(not (% i 3)) "Fizz"] |
||
[True i])))</ |
[True i])))</syntaxhighlight> |
||
=={{header|i}}== |
=={{header|i}}== |
||
< |
<syntaxhighlight lang="i">software { |
||
for each 1 to 100 |
for each 1 to 100 |
||
if i % 15 = 0 |
if i % 15 = 0 |
||
Line 4,670: | Line 4,670: | ||
end |
end |
||
end |
end |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon"># straight-forward modulo tester |
||
procedure main() |
procedure main() |
||
every i := 1 to 100 do |
every i := 1 to 100 do |
||
Line 4,684: | Line 4,684: | ||
else |
else |
||
write(i) |
write(i) |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="icon"># idiomatic modulo tester, 1st alternative |
||
procedure main() |
procedure main() |
||
every i := 1 to 100 do |
every i := 1 to 100 do |
||
write((i % 15 = 0 & "FizzBuzz") | (i % 5 = 0 & "Buzz") | (i % 3 = 0 & "Fizz") | i) |
write((i % 15 = 0 & "FizzBuzz") | (i % 5 = 0 & "Buzz") | (i % 3 = 0 & "Fizz") | i) |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="icon"># idiomatic modulo tester, 2nd alternative |
||
procedure main() |
procedure main() |
||
every i := 1 to 100 do |
every i := 1 to 100 do |
||
Line 4,699: | Line 4,699: | ||
default: i |
default: i |
||
}) |
}) |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="icon"># straight-forward buffer builder |
||
procedure main() |
procedure main() |
||
every i := 1 to 100 do { |
every i := 1 to 100 do { |
||
Line 4,712: | Line 4,712: | ||
write(s) |
write(s) |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="icon"># idiomatic buffer builder, 1st alternative |
||
procedure main() |
procedure main() |
||
every i := 1 to 100 do |
every i := 1 to 100 do |
||
write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i) |
write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i) |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="icon"># idiomatic buffer builder, 2nd alternative |
||
procedure main() |
procedure main() |
||
every i := 1 to 100 do { |
every i := 1 to 100 do { |
||
Line 4,725: | Line 4,725: | ||
write(("" ~= s) | i) |
write(("" ~= s) | i) |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Idris}}== |
=={{header|Idris}}== |
||
< |
<syntaxhighlight lang="idris">partial |
||
fizzBuzz : Nat -> String |
fizzBuzz : Nat -> String |
||
fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz" |
fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz" |
||
Line 4,736: | Line 4,736: | ||
main : IO () |
main : IO () |
||
main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]</ |
main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]</syntaxhighlight> |
||
=={{header|Inform 6}}== |
=={{header|Inform 6}}== |
||
< |
<syntaxhighlight lang="inform6">[ Main i; |
||
for(i = 1: i <= 100: i++) |
for(i = 1: i <= 100: i++) |
||
{ |
{ |
||
Line 4,748: | Line 4,748: | ||
print "^"; |
print "^"; |
||
} |
} |
||
];</ |
];</syntaxhighlight> |
||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
Line 4,754: | Line 4,754: | ||
(Does not work in the current version of Inform 7) |
(Does not work in the current version of Inform 7) |
||
< |
<syntaxhighlight lang="inform7">Home is a room. |
||
When play begins: |
When play begins: |
||
Line 4,767: | Line 4,767: | ||
if printed is false, say N; |
if printed is false, say N; |
||
say "."; |
say "."; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
(Version which is less "programmy", and more in the natural English style of interactive fiction.) |
(Version which is less "programmy", and more in the natural English style of interactive fiction.) |
||
< |
<syntaxhighlight lang="inform7">The space is a room. An item is a kind of thing. In the space are 100 items. |
||
To say the name: |
To say the name: |
||
Line 4,786: | Line 4,786: | ||
end if. |
end if. |
||
When play begins: count. Use no scoring.</ |
When play begins: count. Use no scoring.</syntaxhighlight> |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
Here's one way to do it: |
Here's one way to do it: |
||
< |
<syntaxhighlight lang="io">for(a,1,100, |
||
if(a % 15 == 0) then( |
if(a % 15 == 0) then( |
||
"FizzBuzz" println |
"FizzBuzz" println |
||
Line 4,800: | Line 4,800: | ||
a println |
a println |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
And here's a port of the Ruby version, which I personally prefer: |
And here's a port of the Ruby version, which I personally prefer: |
||
< |
<syntaxhighlight lang="io">a := 0; b := 0 |
||
for(n, 1, 100, |
for(n, 1, 100, |
||
if(a = (n % 3) == 0, "Fizz" print); |
if(a = (n % 3) == 0, "Fizz" print); |
||
Line 4,808: | Line 4,808: | ||
if(a not and b not, n print); |
if(a not and b not, n print); |
||
"\n" print |
"\n" print |
||
)</ |
)</syntaxhighlight> |
||
And here is another more idiomatic version: |
And here is another more idiomatic version: |
||
< |
<syntaxhighlight lang="io">for (n, 1, 100, |
||
fb := list ( |
fb := list ( |
||
if (n % 3 == 0, "Fizz"), |
if (n % 3 == 0, "Fizz"), |
||
Line 4,816: | Line 4,816: | ||
if (fb isEmpty, n, fb join) println |
if (fb isEmpty, n, fb join) println |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Ioke}}== |
=={{header|Ioke}}== |
||
< |
<syntaxhighlight lang="ioke">(1..100) each(x, |
||
cond( |
cond( |
||
(x % 15) zero?, "FizzBuzz" println, |
(x % 15) zero?, "FizzBuzz" println, |
||
Line 4,825: | Line 4,825: | ||
(x % 5) zero?, "Buzz" println |
(x % 5) zero?, "Buzz" println |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Iptscrae}}== |
=={{header|Iptscrae}}== |
||
< |
<syntaxhighlight lang="iptscrae">; FizzBuzz in Iptscrae |
||
1 a = |
1 a = |
||
{ |
{ |
||
Line 4,837: | Line 4,837: | ||
a ++ |
a ++ |
||
} |
} |
||
{ a 100 <= } WHILE</ |
{ a 100 <= } WHILE</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 4,848: | Line 4,848: | ||
Solution _1: Using agenda (@.) as a switch: |
Solution _1: Using agenda (@.) as a switch: |
||
<syntaxhighlight lang="j"> |
|||
<lang j> |
|||
classify =: +/@(1 2 * 0 = 3 5&|~) |
classify =: +/@(1 2 * 0 = 3 5&|~) |
||
(":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100 |
(":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Solution 0 |
Solution 0 |
||
< |
<syntaxhighlight lang="j">> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101</syntaxhighlight> |
||
Solution 1 |
Solution 1 |
||
< |
<syntaxhighlight lang="j">Fizz=: 'Fizz' #~ 0 = 3&| |
||
Buzz=: 'Buzz' #~ 0 = 5&| |
Buzz=: 'Buzz' #~ 0 = 5&| |
||
FizzBuzz=: ": [^:('' -: ]) Fizz,Buzz |
FizzBuzz=: ": [^:('' -: ]) Fizz,Buzz |
||
FizzBuzz"0 >: i.100</ |
FizzBuzz"0 >: i.100</syntaxhighlight> |
||
Solution 2 (has taste of table-driven template programming) |
Solution 2 (has taste of table-driven template programming) |
||
< |
<syntaxhighlight lang="j">CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": ' |
||
NB. Rather (, 0 = +./) than (, +:/) because designed for |
NB. Rather (, 0 = +./) than (, +:/) because designed for |
||
NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7 |
NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7 |
||
FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz') |
FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz') |
||
FizzBuzz"0 >: i.100</ |
FizzBuzz"0 >: i.100</syntaxhighlight> |
||
Solution 3 (depends on an obsolete feature of @ in f`g`h@p) |
Solution 3 (depends on an obsolete feature of @ in f`g`h@p) |
||
< |
<syntaxhighlight lang="j">'`f b fb' =: ('Fizz'"_) ` ('Buzz'"_) ` (f , b) |
||
'`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@) |
'`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@) |
||
FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also: |
FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also: |
||
FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5) |
FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5) |
||
FizzBuzz"0 >: i.100</ |
FizzBuzz"0 >: i.100</syntaxhighlight> |
||
Solution 4 (relatively concise): |
Solution 4 (relatively concise): |
||
< |
<syntaxhighlight lang="j"> ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~ 0 = 3 5 |/ ])i.101 |
||
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 Fiz...</ |
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 Fiz...</syntaxhighlight> |
||
Here's some intermediate results for subexpressions of this last version (but with a shorter list of numbers): |
Here's some intermediate results for subexpressions of this last version (but with a shorter list of numbers): |
||
< |
<syntaxhighlight lang="j"> i.10 |
||
0 1 2 3 4 5 6 7 8 9 |
0 1 2 3 4 5 6 7 8 9 |
||
(3 5 |/ ])i.10 |
(3 5 |/ ])i.10 |
||
Line 4,917: | Line 4,917: | ||
└─┴─┴────┴─┴────┴────┴─┴─┴────┘ |
└─┴─┴────┴─┴────┴────┴─┴─┴────┘ |
||
;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 |
;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 |
||
1 2 Fizz 4 Buzz Fizz 7 8 Fizz</ |
1 2 Fizz 4 Buzz Fizz 7 8 Fizz</syntaxhighlight> |
||
=={{header|Janet}}== |
=={{header|Janet}}== |
||
< |
<syntaxhighlight lang="janet"> |
||
(loop [i :range [1 101] |
(loop [i :range [1 101] |
||
:let [fizz (zero? (% i 3)) |
:let [fizz (zero? (% i 3)) |
||
Line 4,929: | Line 4,929: | ||
buzz "buzz" |
buzz "buzz" |
||
i))) |
i))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java"> |
||
public class FizzBuzz { |
public class FizzBuzz { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
Line 4,948: | Line 4,948: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Or: ''' |
'''Or: ''' |
||
< |
<syntaxhighlight lang="java"> |
||
public class FizzBuzz { |
public class FizzBuzz { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
Line 4,968: | Line 4,968: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Or: ''' |
'''Or: ''' |
||
< |
<syntaxhighlight lang="java"> |
||
public class FizzBuzz { |
public class FizzBuzz { |
||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
Line 4,980: | Line 4,980: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 4,986: | Line 4,986: | ||
===ES5=== |
===ES5=== |
||
< |
<syntaxhighlight lang="javascript">var fizzBuzz = function () { |
||
var i, output; |
var i, output; |
||
for (i = 1; i < 101; i += 1) { |
for (i = 1; i < 101; i += 1) { |
||
Line 4,994: | Line 4,994: | ||
console.log(output || i);//empty string is false, so we short-circuit |
console.log(output || i);//empty string is false, so we short-circuit |
||
} |
} |
||
};</ |
};</syntaxhighlight> |
||
Alternate version with ghetto pattern matching |
Alternate version with ghetto pattern matching |
||
< |
<syntaxhighlight lang="javascript">for (var i = 1; i <= 100; i++) { |
||
console.log({ |
console.log({ |
||
truefalse: 'Fizz', |
truefalse: 'Fizz', |
||
Line 5,003: | Line 5,003: | ||
truetrue: 'FizzBuzz' |
truetrue: 'FizzBuzz' |
||
}[(i%3==0) + '' + (i%5==0)] || i) |
}[(i%3==0) + '' + (i%5==0)] || i) |
||
}</ |
}</syntaxhighlight> |
||
Or very tersely: |
Or very tersely: |
||
< |
<syntaxhighlight lang="javascript">for(i=1;i<101;i++)console.log((x=(i%3?'':'Fizz')+(i%5?'':'Buzz'))?x:i);</syntaxhighlight> |
||
Or with even less characters: |
Or with even less characters: |
||
< |
<syntaxhighlight lang="javascript">for(i=1;i<101;i++)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)</syntaxhighlight> |
||
Or, in a more functional style, without mutations |
Or, in a more functional style, without mutations |
||
< |
<syntaxhighlight lang="javascript">(function rng(i) { |
||
return i ? rng(i - 1).concat(i) : [] |
return i ? rng(i - 1).concat(i) : [] |
||
})(100).map( |
})(100).map( |
||
Line 5,022: | Line 5,022: | ||
) |
) |
||
} |
} |
||
).join(' ')</ |
).join(' ')</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
// FIZZBUZZ -------------------------------------------------------------- |
// FIZZBUZZ -------------------------------------------------------------- |
||
Line 5,060: | Line 5,060: | ||
map(fizzBuzz, enumFromTo(1, 100)) |
map(fizzBuzz, enumFromTo(1, 100)) |
||
); |
); |
||
})();</ |
})();</syntaxhighlight> |
||
A functional implementation: |
A functional implementation: |
||
< |
<syntaxhighlight lang="javascript">const factors = [[3, 'Fizz'], [5, 'Buzz']] |
||
const fizzBuzz = num => factors.map(([factor,text]) => (num % factor)?'':text).join('') || num |
const fizzBuzz = num => factors.map(([factor,text]) => (num % factor)?'':text).join('') || num |
||
const range1 = x => [...Array(x+1).keys()].slice(1) |
const range1 = x => [...Array(x+1).keys()].slice(1) |
||
const outputs = range1(100).map(fizzBuzz) |
const outputs = range1(100).map(fizzBuzz) |
||
console.log(outputs.join('\n'))</ |
console.log(outputs.join('\n'))</syntaxhighlight> |
||
Line 5,075: | Line 5,075: | ||
{{Trans|Python}} |
{{Trans|Python}} |
||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 5,259: | Line 5,259: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
The following program first defines a function "out", that handles the Fizz / Buzz logic, and then loops from 1 to 100 mapping the function onto each number, and printing ("put") the output. |
The following program first defines a function "out", that handles the Fizz / Buzz logic, and then loops from 1 to 100 mapping the function onto each number, and printing ("put") the output. |
||
<syntaxhighlight lang= |
<syntaxhighlight lang="joy">DEFINE out == [[[15 rem null] "FizzBuzz"] |
||
[[ 3 rem null] "Fizz"] |
[[ 3 rem null] "Fizz"] |
||
[[ 5 rem null] "Buzz"] |
[[ 5 rem null] "Buzz"] |
||
Line 5,272: | Line 5,272: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
< |
<syntaxhighlight lang="jq">range(1;101) |
||
| if . % 15 == 0 then "FizzBuzz" |
| if . % 15 == 0 then "FizzBuzz" |
||
elif . % 5 == 0 then "Buzz" |
elif . % 5 == 0 then "Buzz" |
||
elif . % 3 == 0 then "Fizz" |
elif . % 3 == 0 then "Fizz" |
||
else . |
else . |
||
end</ |
end</syntaxhighlight> |
||
Another solution: |
Another solution: |
||
< |
<syntaxhighlight lang="jq">range(100) + 1 | [( |
||
(select(. % 3 == 0) | "Fizz"), |
(select(. % 3 == 0) | "Fizz"), |
||
(select(. % 5 == 0) | "Buzz") |
(select(. % 5 == 0) | "Buzz") |
||
) // tostring] | join("") |
) // tostring] | join("") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 5,291: | Line 5,291: | ||
One basic solution: |
One basic solution: |
||
< |
<syntaxhighlight lang="julia">for i in 1:100 |
||
if i % 15 == 0 |
if i % 15 == 0 |
||
println("FizzBuzz") |
println("FizzBuzz") |
||
Line 5,301: | Line 5,301: | ||
println(i) |
println(i) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Another possible solution: |
Another possible solution: |
||
< |
<syntaxhighlight lang="julia">collect(i % 15 == 0 ? "FizzBuzz" : i % 5 == 0 ? "Buzz" : i % 3 == 0 ? "Fizz" : i for i in 1:100) |> println</syntaxhighlight> |
||
A 3rd possible solution: |
A 3rd possible solution: |
||
< |
<syntaxhighlight lang="julia">fb(i::Integer) = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) * dec(i) ^ (i % 3 != 0 && i % 5 != 0) |
||
for i in 1:100 println(fb(i)) end</ |
for i in 1:100 println(fb(i)) end</syntaxhighlight> |
||
A 4th one: |
A 4th one: |
||
< |
<syntaxhighlight lang="julia">println.(map(fb, 1:100))</syntaxhighlight> |
||
A fifth (DRY, Don't Repeat Yourself) possible solution: |
A fifth (DRY, Don't Repeat Yourself) possible solution: |
||
< |
<syntaxhighlight lang="julia">for i in 1:100 |
||
msg = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) |
msg = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) |
||
println(isempty(msg) ? i : msg) |
println(isempty(msg) ? i : msg) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
===Solution 0=== |
===Solution 0=== |
||
< |
<syntaxhighlight lang="k">`0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101</syntaxhighlight> |
||
===Solution 1=== |
===Solution 1=== |
||
<syntaxhighlight lang="k"> |
|||
<lang k> |
|||
fizzbuzz:{:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]} |
fizzbuzz:{:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]} |
||
fizzbuzz' 1+!100 |
fizzbuzz' 1+!100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Solution 2=== |
===Solution 2=== |
||
< |
<syntaxhighlight lang="k">fizzbuzz:{ |
||
v:1+!x |
v:1+!x |
||
i:(&0=)'v!/:3 5 15 |
i:(&0=)'v!/:3 5 15 |
||
Line 5,337: | Line 5,337: | ||
@[r;i 2;{"FizzBuzz"}]} |
@[r;i 2;{"FizzBuzz"}]} |
||
`0:$fizzbuzz 100</ |
`0:$fizzbuzz 100</syntaxhighlight> |
||
===Solution 3=== |
===Solution 3=== |
||
For kona: < |
For kona: <syntaxhighlight lang="k">{,/$(s;x)@~#s:`Fizz`Buzz@&~x!'3 5}'1+!30</syntaxhighlight> |
||
For k6 and oK, change <code>x!'3 5</code> to <code>3 5!'x</code>. |
For k6 and oK, change <code>x!'3 5</code> to <code>3 5!'x</code>. |
||
Line 5,347: | Line 5,347: | ||
This will only work up to 100 because Kamailio terminates all while loops after 100 iterations. |
This will only work up to 100 because Kamailio terminates all while loops after 100 iterations. |
||
< |
<syntaxhighlight lang="kamailio"># FizzBuzz |
||
log_stderror=yes |
log_stderror=yes |
||
loadmodule "pv" |
loadmodule "pv" |
||
Line 5,366: | Line 5,366: | ||
$var(i) = $var(i) + 1; |
$var(i) = $var(i) + 1; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Kaya}}== |
=={{header|Kaya}}== |
||
< |
<syntaxhighlight lang="kaya">// fizzbuzz in Kaya |
||
program fizzbuzz; |
program fizzbuzz; |
||
Line 5,388: | Line 5,388: | ||
Void main() { |
Void main() { |
||
fizzbuzz(100); |
fizzbuzz(100); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|KL1}}== |
=={{header|KL1}}== |
||
< |
<syntaxhighlight lang="prolog"> |
||
:- module main. |
:- module main. |
||
Line 5,429: | Line 5,429: | ||
display(Rest). |
display(Rest). |
||
display([]). |
display([]). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Klong}}== |
=={{header|Klong}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang k> |
|||
{:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100 |
{:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
===Imperative solution=== |
===Imperative solution=== |
||
< |
<syntaxhighlight lang="scala">fun fizzBuzz() { |
||
for (number in 1..100) { |
for (number in 1..100) { |
||
println( |
println( |
||
Line 5,450: | Line 5,450: | ||
) |
) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Functional solution 1=== |
===Functional solution 1=== |
||
< |
<syntaxhighlight lang="scala">fun fizzBuzz1() { |
||
fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString() |
fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString() |
||
fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x |
fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x |
||
Line 5,459: | Line 5,459: | ||
(1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) } |
(1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) } |
||
}</ |
}</syntaxhighlight> |
||
===Functional solution 2=== |
===Functional solution 2=== |
||
< |
<syntaxhighlight lang="scala">fun fizzBuzz2() { |
||
fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x |
fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x |
||
fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x |
fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x |
||
Line 5,472: | Line 5,472: | ||
.map { none(it) } |
.map { none(it) } |
||
.forEach { println(it) } |
.forEach { println(it) } |
||
}</ |
}</syntaxhighlight> |
||
===Short version with mapOf=== |
===Short version with mapOf=== |
||
< |
<syntaxhighlight lang="scala"> |
||
fun fizzBuzz() { |
fun fizzBuzz() { |
||
(1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) } |
(1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) } |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|KQL}}== |
=={{header|KQL}}== |
||
< |
<syntaxhighlight lang="kql"> |
||
range i from 1 to 100 step 1 |
range i from 1 to 100 step 1 |
||
| project Result = |
| project Result = |
||
Line 5,491: | Line 5,491: | ||
tostring(i) |
tostring(i) |
||
) |
) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|KSI}}== |
=={{header|KSI}}== |
||
< |
<syntaxhighlight lang="ksi"> |
||
`plain |
`plain |
||
[1 100] `for pos : n ~ |
[1 100] `for pos : n ~ |
||
Line 5,502: | Line 5,502: | ||
(out `or n) #write_ln # |
(out `or n) #write_ln # |
||
; |
; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
Line 5,509: | Line 5,509: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
<syntaxhighlight lang="scheme"> |
|||
<lang Scheme> |
|||
1. direct: |
1. direct: |
||
Line 5,543: | Line 5,543: | ||
-> same as above. |
-> same as above. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|langur}}== |
=={{header|langur}}== |
||
< |
<syntaxhighlight lang="langur">for .i of 100 { |
||
writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i) |
writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i) |
||
}</ |
}</syntaxhighlight> |
||
{{works with|langur|0.8.1}} |
{{works with|langur|0.8.1}} |
||
< |
<syntaxhighlight lang="langur">for .i of 100 { |
||
writeln if(.i div 15: "FizzBuzz"; .i div 5: "Buzz"; .i div 3: "Fizz"; .i) |
writeln if(.i div 15: "FizzBuzz"; .i div 5: "Buzz"; .i div 3: "Fizz"; .i) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">with i in generateSeries(1, 100) |
||
select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)</ |
select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)</syntaxhighlight> |
||
=={{header|LaTeX}}== |
=={{header|LaTeX}}== |
||
Line 5,563: | Line 5,563: | ||
{{libheader|intcalc}} |
{{libheader|intcalc}} |
||
This version uses the ifthen and intcalc packages. There sure are more native solutions including solutions in plain TeX, but for me this is a readable and comprehensible one. |
This version uses the ifthen and intcalc packages. There sure are more native solutions including solutions in plain TeX, but for me this is a readable and comprehensible one. |
||
< |
<syntaxhighlight lang="latex">\documentclass{minimal} |
||
\usepackage{ifthen} |
\usepackage{ifthen} |
||
\usepackage{intcalc} |
\usepackage{intcalc} |
||
Line 5,581: | Line 5,581: | ||
\begin{document} |
\begin{document} |
||
\fizzBuzz{101} |
\fizzBuzz{101} |
||
\end{document}</ |
\end{document}</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
Line 5,587: | Line 5,587: | ||
=={{header|LIL}}== |
=={{header|LIL}}== |
||
< |
<syntaxhighlight lang="tcl"># fizzbuzz in LIL |
||
for {set i 1} {$i <= 100} {inc i} { |
for {set i 1} {$i <= 100} {inc i} { |
||
set show "" |
set show "" |
||
Line 5,594: | Line 5,594: | ||
if {[expr [length $show] == 0]} {set show $i} |
if {[expr [length $show] == 0]} {set show $i} |
||
print $show |
print $show |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,616: | Line 5,616: | ||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">repeat with i = 1 to 100 |
||
switch |
switch |
||
case i mod 15 = 0 |
case i mod 15 = 0 |
||
Line 5,631: | Line 5,631: | ||
end switch |
end switch |
||
end repeat |
end repeat |
||
put fizzbuzz</ |
put fizzbuzz</syntaxhighlight> |
||
=={{header|LiveScript}}== |
=={{header|LiveScript}}== |
||
See: http://livescript.net/blog/fizzbuzzbazz.html |
See: http://livescript.net/blog/fizzbuzzbazz.html |
||
< |
<syntaxhighlight lang="livescript">[1 to 100] map -> [k + \zz for k, v of {Fi: 3, Bu: 5} | it % v < 1] * '' || it</syntaxhighlight> |
||
=={{header|LLVM}}== |
=={{header|LLVM}}== |
||
< |
<syntaxhighlight lang="llvm">; ModuleID = 'fizzbuzz.c' |
||
; source_filename = "fizzbuzz.c" |
; source_filename = "fizzbuzz.c" |
||
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128" |
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128" |
||
Line 5,738: | Line 5,738: | ||
!0 = !{i32 1, !"wchar_size", i32 2} |
!0 = !{i32 1, !"wchar_size", i32 2} |
||
!1 = !{i32 7, !"PIC Level", i32 2} |
!1 = !{i32 7, !"PIC Level", i32 2} |
||
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</ |
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</syntaxhighlight> |
||
=={{header|Lobster}}== |
=={{header|Lobster}}== |
||
< |
<syntaxhighlight lang="lobster">include "std.lobster" |
||
forbias(100, 1) i: |
forbias(100, 1) i: |
||
fb := (i % 3 == 0 and "fizz" or "") + |
fb := (i % 3 == 0 and "fizz" or "") + |
||
(i % 5 == 0 and "buzz" or "") |
(i % 5 == 0 and "buzz" or "") |
||
print fb.length and fb or "" + i</ |
print fb.length and fb or "" + i</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to fizzbuzz :n |
||
output cond [ [[equal? 0 modulo :n 15] "FizzBuzz] |
output cond [ [[equal? 0 modulo :n 15] "FizzBuzz] |
||
[[equal? 0 modulo :n 5] "Buzz] |
[[equal? 0 modulo :n 5] "Buzz] |
||
Line 5,756: | Line 5,756: | ||
end |
end |
||
repeat 100 [print fizzbuzz #]</ |
repeat 100 [print fizzbuzz #]</syntaxhighlight> |
||
"cond" was undefined in Joshua Bell's online interpreter. So here is a version that works there. It also works in UCB logo by using # instead of "repcount". This version also factors away modulo 15: |
"cond" was undefined in Joshua Bell's online interpreter. So here is a version that works there. It also works in UCB logo by using # instead of "repcount". This version also factors away modulo 15: |
||
< |
<syntaxhighlight lang="logo">to fizzbuzz :n |
||
make "c " |
make "c " |
||
if equal? 0 modulo :n 5 [make "c "Buzz] |
if equal? 0 modulo :n 5 [make "c "Buzz] |
||
Line 5,765: | Line 5,765: | ||
end |
end |
||
repeat 100 [print fizzbuzz repcount]</ |
repeat 100 [print fizzbuzz repcount]</syntaxhighlight> |
||
Lhogho can use the above code, except that 'modulo' must be replaced with 'remainder'. |
Lhogho can use the above code, except that 'modulo' must be replaced with 'remainder'. |
||
Line 5,772: | Line 5,772: | ||
=={{header|LSE}}== |
=={{header|LSE}}== |
||
< |
<syntaxhighlight lang="lse">1* FIZZBUZZ en L.S.E. |
||
10 CHAINE FB |
10 CHAINE FB |
||
20 FAIRE 45 POUR I_1 JUSQUA 100 |
20 FAIRE 45 POUR I_1 JUSQUA 100 |
||
Line 5,780: | Line 5,780: | ||
50 TERMINER |
50 TERMINER |
||
100 PROCEDURE &MOD(A,B) LOCAL A,B |
100 PROCEDURE &MOD(A,B) LOCAL A,B |
||
110 RESULTAT A-B*ENT(A/B)</ |
110 RESULTAT A-B*ENT(A/B)</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
===If/else Ladder=== |
===If/else Ladder=== |
||
< |
<syntaxhighlight lang="lua">for i = 1, 100 do |
||
if i % 15 == 0 then |
if i % 15 == 0 then |
||
print("FizzBuzz") |
print("FizzBuzz") |
||
Line 5,794: | Line 5,794: | ||
print(i) |
print(i) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
===Concatenation=== |
===Concatenation=== |
||
< |
<syntaxhighlight lang="lua">for i = 1, 100 do |
||
output = "" |
output = "" |
||
if i % 3 == 0 then |
if i % 3 == 0 then |
||
Line 5,808: | Line 5,808: | ||
end |
end |
||
print(output) |
print(output) |
||
end</ |
end</syntaxhighlight> |
||
===Quasi bit field=== |
===Quasi bit field=== |
||
< |
<syntaxhighlight lang="lua">word = {"Fizz", "Buzz", "FizzBuzz"} |
||
for i = 1, 100 do |
for i = 1, 100 do |
||
print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i) |
print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i) |
||
end</ |
end</syntaxhighlight> |
||
===Lookup table=== |
===Lookup table=== |
||
< |
<syntaxhighlight lang="lua">local t = { |
||
[0] = "FizzBuzz", |
[0] = "FizzBuzz", |
||
[3] = "Fizz", |
[3] = "Fizz", |
||
Line 5,830: | Line 5,830: | ||
for i = 1, 100 do |
for i = 1, 100 do |
||
print(t[i%15] or i) |
print(t[i%15] or i) |
||
end</ |
end</syntaxhighlight> |
||
=== Fast Version without Modulo === |
=== Fast Version without Modulo === |
||
< |
<syntaxhighlight lang="lua"> |
||
#!/usr/bin/env luajit |
#!/usr/bin/env luajit |
||
local to=arg[1] or tonumber(arg[1]) or 100 |
local to=arg[1] or tonumber(arg[1]) or 100 |
||
Line 5,854: | Line 5,854: | ||
io.write(", ") |
io.write(", ") |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 5,863: | Line 5,863: | ||
=={{header|Luck}}== |
=={{header|Luck}}== |
||
< |
<syntaxhighlight lang="luck">for i in range(1,101) do ( |
||
if i%15 == 0 then print("FizzBuzz") |
if i%15 == 0 then print("FizzBuzz") |
||
else if i%3 == 0 then print("Fizz") |
else if i%3 == 0 then print("Fizz") |
||
else if i%5 == 0 then print("Buzz") |
else if i%5 == 0 then print("Buzz") |
||
else print(i) |
else print(i) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
\\ one line, hard to read |
\\ one line, hard to read |
||
For i=1 to 100 {If i mod 3=0 Then {if i mod 5=0 Then Print "FizzBuzz", Else Print "Fizz",} Else {if i mod 5=0 Then Print "Buzz", else print i, } } : Print |
For i=1 to 100 {If i mod 3=0 Then {if i mod 5=0 Then Print "FizzBuzz", Else Print "Fizz",} Else {if i mod 5=0 Then Print "Buzz", else print i, } } : Print |
||
Line 5,890: | Line 5,890: | ||
If a$<>"" Then Print a$, else Print i, |
If a$<>"" Then Print a$, else Print i, |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">define(`for', |
||
`ifelse($#,0,``$0'', |
`ifelse($#,0,``$0'', |
||
`ifelse(eval($2<=$3),1, |
`ifelse(eval($2<=$3),1, |
||
Line 5,902: | Line 5,902: | ||
`ifelse(eval(x%3==0),1,Fizz, |
`ifelse(eval(x%3==0),1,Fizz, |
||
`ifelse(eval(x%5==0),1,Buzz,x)')') |
`ifelse(eval(x%5==0),1,Buzz,x)')') |
||
')</ |
')</syntaxhighlight> |
||
=={{header|make}}== |
=={{header|make}}== |
||
{{works with|BSD make}} |
{{works with|BSD make}} |
||
{{libheader|jot}} |
{{libheader|jot}} |
||
< |
<syntaxhighlight lang="make">MOD3 = 0 |
||
MOD5 = 0 |
MOD5 = 0 |
||
ALL != jot 100 |
ALL != jot 100 |
||
Line 5,934: | Line 5,934: | ||
. endif |
. endif |
||
.endfor</ |
.endfor</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
One line: |
One line: |
||
< |
<syntaxhighlight lang="maple">seq(print(`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n))),n=1..100):</syntaxhighlight> |
||
With a fizzbuzz function defined: |
With a fizzbuzz function defined: |
||
< |
<syntaxhighlight lang="maple">fizzbuzz1 := n->`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n)): |
||
for i to 100 do fizzbuzz1(i); od;</ |
for i to 100 do fizzbuzz1(i); od;</syntaxhighlight> |
||
Using piecewise: |
Using piecewise: |
||
< |
<syntaxhighlight lang="maple">fizzbuzz2 := n->piecewise(modp(n,15)=0,"FizzBuzz",modp(n,3)=0,"Fizz",modp(n,5)=0,"Buzz",n): |
||
for i to 100 do fizzbuzz2(i); od;</ |
for i to 100 do fizzbuzz2(i); od;</syntaxhighlight> |
||
Using conventional if/then branches: |
Using conventional if/then branches: |
||
< |
<syntaxhighlight lang="maple">fizzbuzz3 := proc(n) local r; |
||
r:=map2(modp,n,[3,5]); |
r:=map2(modp,n,[3,5]); |
||
if r=[0,0] then "FizzBuzz" |
if r=[0,0] then "FizzBuzz" |
||
Line 5,953: | Line 5,953: | ||
else n fi; |
else n fi; |
||
end proc: |
end proc: |
||
for i to 100 do fizzbuzz3(i); od;</ |
for i to 100 do fizzbuzz3(i); od;</syntaxhighlight> |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Do[Print[Which[Mod[i, 15] == 0, "FizzBuzz", Mod[i, 5] == 0, "Buzz", Mod[i, 3] == 0, "Fizz", True, i]], {i, 100}]</syntaxhighlight> |
||
Using rules, |
Using rules, |
||
< |
<syntaxhighlight lang="mathematica">fizz[i_] := Mod[i, 3] == 0 |
||
buzz[i_] := Mod[i, 5] == 0 |
buzz[i_] := Mod[i, 5] == 0 |
||
Range[100] /. {i_ /; fizz[i]&&buzz[i] :> "FizzBuzz", \ |
Range[100] /. {i_ /; fizz[i]&&buzz[i] :> "FizzBuzz", \ |
||
i_?fizz :> "Fizz", i_?buzz :> "Buzz"}</ |
i_?fizz :> "Fizz", i_?buzz :> "Buzz"}</syntaxhighlight> |
||
Using rules, but different approach: |
Using rules, but different approach: |
||
< |
<syntaxhighlight lang="mathematica">SetAttributes[f,Listable] |
||
f[n_ /; Mod[n, 15] == 0] := "FizzBuzz"; |
f[n_ /; Mod[n, 15] == 0] := "FizzBuzz"; |
||
f[n_ /; Mod[n, 3] == 0] := "Fizz"; |
f[n_ /; Mod[n, 3] == 0] := "Fizz"; |
||
Line 5,969: | Line 5,969: | ||
f[n_] := n; |
f[n_] := n; |
||
f[Range[100]]</ |
f[Range[100]]</syntaxhighlight> |
||
An extendible version using Table |
An extendible version using Table |
||
< |
<syntaxhighlight lang="mathematica">Table[If[# === "", i, #]&@StringJoin[ |
||
Table[If[Divisible[i, First@nw], Last@nw, ""], |
Table[If[Divisible[i, First@nw], Last@nw, ""], |
||
{nw, {{3, "Fizz"}, {5, "Buzz"}}}]], |
{nw, {{3, "Fizz"}, {5, "Buzz"}}}]], |
||
{i, 1, 100}]</ |
{i, 1, 100}]</syntaxhighlight> |
||
Another one-liner using Map (the /@ operator shorthand of it) and a pure function with a very readable Which |
Another one-liner using Map (the /@ operator shorthand of it) and a pure function with a very readable Which |
||
< |
<syntaxhighlight lang="mathematica"> Which[ Mod[#,15] == 0, "FizzBuzz", Mod[#, 3] == 0, "Fizz", Mod[#,5]==0, "Buzz", True, #]& /@ Range[1,100] </syntaxhighlight> |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
There are more sophisticated solutions to this task, but in the spirit of "lowest level of comprehension required to illustrate adequacy" this is what one might expect from a novice programmer (with a little variation in how the strings are stored and displayed). |
There are more sophisticated solutions to this task, but in the spirit of "lowest level of comprehension required to illustrate adequacy" this is what one might expect from a novice programmer (with a little variation in how the strings are stored and displayed). |
||
< |
<syntaxhighlight lang="matlab">function fizzBuzz() |
||
for i = (1:100) |
for i = (1:100) |
||
if mod(i,15) == 0 |
if mod(i,15) == 0 |
||
Line 5,993: | Line 5,993: | ||
end |
end |
||
fprintf('\n'); |
fprintf('\n'); |
||
end</ |
end</syntaxhighlight> |
||
Here's a more extendible version that uses disp() to print the output: |
Here's a more extendible version that uses disp() to print the output: |
||
< |
<syntaxhighlight lang="matlab">function out = fizzbuzzS() |
||
nums = [3, 5]; |
nums = [3, 5]; |
||
words = {'fizz', 'buzz'}; |
words = {'fizz', 'buzz'}; |
||
Line 6,011: | Line 6,011: | ||
end |
end |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">for n:1 thru 100 do |
||
if mod(n, 15) = 0 then (sprint("FizzBuzz"), newline()) |
if mod(n, 15) = 0 then (sprint("FizzBuzz"), newline()) |
||
elseif mod(n, 3) = 0 then (sprint("Fizz"), newline()) |
elseif mod(n, 3) = 0 then (sprint("Fizz"), newline()) |
||
elseif mod(n,5) = 0 then (sprint("Buzz"), newline()) |
elseif mod(n,5) = 0 then (sprint("Buzz"), newline()) |
||
else (sprint(n), newline());</ |
else (sprint(n), newline());</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
< |
<syntaxhighlight lang="maxscript">for i in 1 to 100 do |
||
( |
( |
||
case of |
case of |
||
Line 6,030: | Line 6,030: | ||
default: (print i) |
default: (print i) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|MEL}}== |
=={{header|MEL}}== |
||
< |
<syntaxhighlight lang="mel">for($i=1; $i<=100; $i++) |
||
{ |
{ |
||
if($i % 15 == 0) |
if($i % 15 == 0) |
||
Line 6,043: | Line 6,043: | ||
else |
else |
||
print ($i + "\n"); |
print ($i + "\n"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury">:- module fizzbuzz. |
||
:- interface. |
:- interface. |
||
:- import_module io. |
:- import_module io. |
||
Line 6,076: | Line 6,076: | ||
else |
else |
||
true |
true |
||
).</ |
).</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
< |
<syntaxhighlight lang="metafont">for i := 1 upto 100: |
||
message if i mod 15 = 0: "FizzBuzz" & |
message if i mod 15 = 0: "FizzBuzz" & |
||
elseif i mod 3 = 0: "Fizz" & |
elseif i mod 3 = 0: "Fizz" & |
||
Line 6,085: | Line 6,085: | ||
else: decimal i & fi ""; |
else: decimal i & fi ""; |
||
endfor |
endfor |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Microsoft Small Basic}}== |
=={{header|Microsoft Small Basic}}== |
||
{{trans|GW-BASIC}} |
{{trans|GW-BASIC}} |
||
< |
<syntaxhighlight lang="microsoftsmallbasic"> |
||
For n = 1 To 100 |
For n = 1 To 100 |
||
op = "" |
op = "" |
||
Line 6,104: | Line 6,104: | ||
EndIf |
EndIf |
||
EndFor |
EndFor |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
< |
<syntaxhighlight lang="min">0 ( |
||
succ false :hit |
succ false :hit |
||
(3 mod 0 ==) ("Fizz" print! true @hit) when |
(3 mod 0 ==) ("Fizz" print! true @hit) when |
||
(5 mod 0 ==) ("Buzz" print! true @hit) when |
(5 mod 0 ==) ("Buzz" print! true @hit) when |
||
(hit) (print) unless newline |
(hit) (print) unless newline |
||
) 100 times</ |
) 100 times</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">for i in range(1,100) |
||
if i % 15 == 0 then |
if i % 15 == 0 then |
||
print "FizzBuzz" |
print "FizzBuzz" |
||
Line 6,126: | Line 6,126: | ||
print i |
print i |
||
end if |
end if |
||
end for</ |
end for</syntaxhighlight> |
||
=={{header|MIPS Assembly}}== |
=={{header|MIPS Assembly}}== |
||
< |
<syntaxhighlight lang="mips"> |
||
################################# |
################################# |
||
# Fizz Buzz # |
# Fizz Buzz # |
||
Line 6,204: | Line 6,204: | ||
li $v0,10 |
li $v0,10 |
||
syscall |
syscall |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mirah}}== |
=={{header|Mirah}}== |
||
< |
<syntaxhighlight lang="mirah">1.upto(100) do |n| |
||
print "Fizz" if a = ((n % 3) == 0) |
print "Fizz" if a = ((n % 3) == 0) |
||
print "Buzz" if b = ((n % 5) == 0) |
print "Buzz" if b = ((n % 5) == 0) |
||
print n unless (a || b) |
print n unless (a || b) |
||
print "\n" |
print "\n" |
||
end</ |
end</syntaxhighlight> |
||
A little more straight forward: |
A little more straight forward: |
||
< |
<syntaxhighlight lang="mirah">1.upto(100) do |n| |
||
if (n % 15) == 0 |
if (n % 15) == 0 |
||
puts "FizzBuzz" |
puts "FizzBuzz" |
||
Line 6,225: | Line 6,225: | ||
puts n |
puts n |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|ML}}== |
=={{header|ML}}== |
||
==={{header|Standard ML}}=== |
==={{header|Standard ML}}=== |
||
First using two helper functions, one for deciding what to output and another for performing recursion with an auxiliary argument j. |
First using two helper functions, one for deciding what to output and another for performing recursion with an auxiliary argument j. |
||
< |
<syntaxhighlight lang="sml">local |
||
fun fbstr i = |
fun fbstr i = |
||
case (i mod 3 = 0, i mod 5 = 0) of |
case (i mod 3 = 0, i mod 5 = 0) of |
||
Line 6,243: | Line 6,243: | ||
fun fizzbuzz n = fizzbuzz' (n, 1) |
fun fizzbuzz n = fizzbuzz' (n, 1) |
||
val _ = fizzbuzz 100 |
val _ = fizzbuzz 100 |
||
end</ |
end</syntaxhighlight> |
||
Second using the standard-library combinator List.tabulate and a helper function, fb, that calculates and prints the output. |
Second using the standard-library combinator List.tabulate and a helper function, fb, that calculates and prints the output. |
||
< |
<syntaxhighlight lang="sml">local |
||
fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true) |
fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true) |
||
val buzz = i mod 5 = 0 andalso (print "Buzz"; true) |
val buzz = i mod 5 = 0 andalso (print "Buzz"; true) |
||
Line 6,253: | Line 6,253: | ||
fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ()) |
fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ()) |
||
val _ = fizzbuzz 100 |
val _ = fizzbuzz 100 |
||
end</ |
end</syntaxhighlight> |
||
==={{header|mLite}}=== |
==={{header|mLite}}=== |
||
< |
<syntaxhighlight lang="ocaml">local |
||
fun fizzbuzz' |
fun fizzbuzz' |
||
(x mod 15 = 0) = "FizzBuzz" |
(x mod 15 = 0) = "FizzBuzz" |
||
Line 6,271: | Line 6,271: | ||
println ` fizzbuzz ` iota 100; |
println ` fizzbuzz ` iota 100; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MMIX}}== |
=={{header|MMIX}}== |
||
< |
<syntaxhighlight lang="mmix">t IS $255 |
||
Ja IS $127 |
Ja IS $127 |
||
Line 6,336: | Line 6,336: | ||
JMP 1B % repeat for next i |
JMP 1B % repeat for next i |
||
4H XOR t,t,t |
4H XOR t,t,t |
||
TRAP 0,Halt,0 % exit(0)</ |
TRAP 0,Halt,0 % exit(0)</syntaxhighlight> |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE Fizzbuzz; |
||
FROM FormatString IMPORT FormatString; |
FROM FormatString IMPORT FormatString; |
||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
||
Line 6,384: | Line 6,384: | ||
ReadChar |
ReadChar |
||
END Fizzbuzz.</ |
END Fizzbuzz.</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">MODULE Fizzbuzz EXPORTS Main; |
||
IMPORT IO; |
IMPORT IO; |
||
Line 6,404: | Line 6,404: | ||
END; |
END; |
||
END; |
END; |
||
END Fizzbuzz.</ |
END Fizzbuzz.</syntaxhighlight> |
||
=={{header|Monte}}== |
=={{header|Monte}}== |
||
< |
<syntaxhighlight lang="monte">def fizzBuzz(top): |
||
var t := 1 |
var t := 1 |
||
while (t < top): |
while (t < top): |
||
Line 6,421: | Line 6,421: | ||
fizzBuzz(100) |
fizzBuzz(100) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MontiLang}}== |
=={{header|MontiLang}}== |
||
< |
<syntaxhighlight lang="montilang">&DEFINE LOOP 100& |
||
1 VAR i . |
1 VAR i . |
||
Line 6,447: | Line 6,447: | ||
ENDIF |
ENDIF |
||
i 1 + VAR i . |
i 1 + VAR i . |
||
ENDFOR</ |
ENDFOR</syntaxhighlight> |
||
=={{header|MoonScript}}== |
=={{header|MoonScript}}== |
||
< |
<syntaxhighlight lang="moonscript">for i = 1,100 |
||
print ((a) -> a == "" and i or a) table.concat { |
print ((a) -> a == "" and i or a) table.concat { |
||
i % 3 == 0 and "Fizz" or "" |
i % 3 == 0 and "Fizz" or "" |
||
i % 5 == 0 and "Buzz" or ""}</ |
i % 5 == 0 and "Buzz" or ""}</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<syntaxhighlight lang="mumps">FIZZBUZZ |
||
NEW I |
NEW I |
||
FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I) |
FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I) |
||
KILL I |
KILL I |
||
QUIT</ |
QUIT</syntaxhighlight> |
||
< |
<syntaxhighlight lang="mumps">fizzbuzz |
||
for i=1:1:100 do write ! |
for i=1:1:100 do write ! |
||
. write:(i#3)&(i#5) i write:'(i#3) "Fizz" write:'(i#5) "Buzz"</ |
. write:(i#3)&(i#5) i write:'(i#3) "Fizz" write:'(i#5) "Buzz"</syntaxhighlight> |
||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
< |
<syntaxhighlight lang="nanoquery">for i in range(1, 100) |
||
if ((i % 3) = 0) and ((i % 5) = 0) |
if ((i % 3) = 0) and ((i % 5) = 0) |
||
println "FizzBuzz" |
println "FizzBuzz" |
||
Line 6,478: | Line 6,478: | ||
println i |
println i |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|NATURAL}}== |
=={{header|NATURAL}}== |
||
<syntaxhighlight lang="natural"> |
|||
<lang NATURAL> |
|||
DEFINE DATA |
DEFINE DATA |
||
LOCAL |
LOCAL |
||
Line 6,515: | Line 6,515: | ||
* |
* |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
< |
<syntaxhighlight lang="neko">var i = 1 |
||
while(i < 100) { |
while(i < 100) { |
||
Line 6,532: | Line 6,532: | ||
i ++= 1 |
i ++= 1 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
The naive approach: |
The naive approach: |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
Line 6,554: | Line 6,554: | ||
WriteLine($"$(FizzBuzz(i))") |
WriteLine($"$(FizzBuzz(i))") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
A much slicker approach is [http://www.dreamincode.net/forums/blog/217/entry-3539-fizzbuzz-in-nemerle/ posted here] |
A much slicker approach is [http://www.dreamincode.net/forums/blog/217/entry-3539-fizzbuzz-in-nemerle/ posted here] |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">loop j=1 for 100 |
||
select |
select |
||
when j//15==0 then say 'FizzBuzz' |
when j//15==0 then say 'FizzBuzz' |
||
Line 6,565: | Line 6,565: | ||
otherwise say j.right(4) |
otherwise say j.right(4) |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Never}}== |
=={{header|Never}}== |
||
< |
<syntaxhighlight lang="fsharp">func fizz_buzz() -> int |
||
{ |
{ |
||
var i = 1; |
var i = 1; |
||
Line 6,600: | Line 6,600: | ||
0 |
0 |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,635: | Line 6,635: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(dotimes (i 100) |
||
(println |
(println |
||
(cond |
(cond |
||
Line 6,641: | Line 6,641: | ||
((= 0 (% i 3)) "Fizz") |
((= 0 (% i 3)) "Fizz") |
||
((= 0 (% i 5)) "Buzz") |
((= 0 (% i 5)) "Buzz") |
||
('t i))))</ |
('t i))))</syntaxhighlight> |
||
=={{header|NewtonScript}}== |
=={{header|NewtonScript}}== |
||
< |
<syntaxhighlight lang="newton">for i := 1 to 100 do |
||
begin |
begin |
||
if i mod 15 = 0 then |
if i mod 15 = 0 then |
||
Line 6,655: | Line 6,655: | ||
print(i); |
print(i); |
||
print("\n") |
print("\n") |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Nickle}}== |
=={{header|Nickle}}== |
||
< |
<syntaxhighlight lang="nickle">/* Fizzbuzz in nickle */ |
||
void function fizzbuzz(size) { |
void function fizzbuzz(size) { |
||
Line 6,669: | Line 6,669: | ||
} |
} |
||
fizzbuzz(1000);</ |
fizzbuzz(1000);</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nim">for i in 1..100: |
||
if i mod 15 == 0: |
if i mod 15 == 0: |
||
echo("FizzBuzz") |
echo("FizzBuzz") |
||
Line 6,681: | Line 6,681: | ||
echo("Buzz") |
echo("Buzz") |
||
else: |
else: |
||
echo(i)</ |
echo(i)</syntaxhighlight> |
||
===Without Modulus=== |
===Without Modulus=== |
||
< |
<syntaxhighlight lang="nim">var messages = @["", "Fizz", "Buzz", "FizzBuzz"] |
||
var acc = 810092048 |
var acc = 810092048 |
||
for i in 1..100: |
for i in 1..100: |
||
var c = acc and 3 |
var c = acc and 3 |
||
echo(if c == 0: $i else: messages[c]) |
echo(if c == 0: $i else: messages[c]) |
||
acc = acc shr 2 or c shl 28</ |
acc = acc shr 2 or c shl 28</syntaxhighlight> |
||
===Using macro=== |
===Using macro=== |
||
Computes everything at compile time. |
Computes everything at compile time. |
||
< |
<syntaxhighlight lang="nim">import macros |
||
macro FizzBuzz(N): untyped = |
macro FizzBuzz(N): untyped = |
||
var source = "" |
var source = "" |
||
Line 6,709: | Line 6,709: | ||
result = parseStmt(source) |
result = parseStmt(source) |
||
FizzBuzz(100)</ |
FizzBuzz(100)</syntaxhighlight> |
||
=={{header|Nix}}== |
=={{header|Nix}}== |
||
< |
<syntaxhighlight lang="nix">with (import <nixpkgs> { }).lib; |
||
with builtins; |
with builtins; |
||
let |
let |
||
Line 6,728: | Line 6,728: | ||
fizzbuzz { x = x + 1; } else ""); |
fizzbuzz { x = x + 1; } else ""); |
||
in |
in |
||
fizzbuzz { }</ |
fizzbuzz { }</syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
< |
<syntaxhighlight lang="oberon2">MODULE FizzBuzz; |
||
IMPORT Out; |
IMPORT Out; |
||
Line 6,750: | Line 6,750: | ||
Out.Ln |
Out.Ln |
||
END |
END |
||
END FizzBuzz.</ |
END FizzBuzz.</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">bundle Default { |
||
class Fizz { |
class Fizz { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
Line 6,772: | Line 6,772: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
< |
<syntaxhighlight lang="c">// FizzBuzz in Objective-C |
||
#import <Foundation/Foundation.h> |
#import <Foundation/Foundation.h> |
||
Line 6,790: | Line 6,790: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 6,796: | Line 6,796: | ||
Idiomatic OCaml to solve the stated problem: |
Idiomatic OCaml to solve the stated problem: |
||
< |
<syntaxhighlight lang="ocaml">let fizzbuzz i = |
||
match i mod 3, i mod 5 with |
match i mod 3, i mod 5 with |
||
0, 0 -> "FizzBuzz" |
0, 0 -> "FizzBuzz" |
||
Line 6,804: | Line 6,804: | ||
let _ = |
let _ = |
||
for i = 1 to 100 do print_endline (fizzbuzz i) done</ |
for i = 1 to 100 do print_endline (fizzbuzz i) done</syntaxhighlight> |
||
With a view toward extensibility, there are many approaches: monadic, list of rules, ... here we'll use a piped sequence of rules to define a new "fizzbuzz" function: |
With a view toward extensibility, there are many approaches: monadic, list of rules, ... here we'll use a piped sequence of rules to define a new "fizzbuzz" function: |
||
< |
<syntaxhighlight lang="ocaml">(* Useful rule declaration: "cond => f", 'cond'itionally applies 'f' to 'a'ccumulated value *) |
||
let (=>) cond f a = if cond then f a else a |
let (=>) cond f a = if cond then f a else a |
||
let append s a = a^s |
let append s a = a^s |
||
Line 6,816: | Line 6,816: | ||
|> (i mod 5 = 0 => append "Buzz") |
|> (i mod 5 = 0 => append "Buzz") |
||
|> (function "" -> string_of_int i |
|> (function "" -> string_of_int i |
||
| s -> s)</ |
| s -> s)</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">for i = 1:100 |
||
if ( mod(i,15) == 0 ) |
if ( mod(i,15) == 0 ) |
||
disp("FizzBuzz"); |
disp("FizzBuzz"); |
||
Line 6,829: | Line 6,829: | ||
disp(i) |
disp(i) |
||
endif |
endif |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: fizzbuzz |
||
| i | |
| i | |
||
100 loop: i [ |
100 loop: i [ |
||
Line 6,840: | Line 6,840: | ||
i 5 mod ifZero: [ "Buzz" + ] |
i 5 mod ifZero: [ "Buzz" + ] |
||
dup ifNull: [ drop i ] . |
dup ifNull: [ drop i ] . |
||
] ; </ |
] ; </syntaxhighlight> |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(for-each (lambda (x) |
(for-each (lambda (x) |
||
(print (cond |
(print (cond |
||
Line 6,855: | Line 6,855: | ||
x)))) |
x)))) |
||
(iota 100)) |
(iota 100)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OOC}}== |
=={{header|OOC}}== |
||
< |
<syntaxhighlight lang="ooc">fizz: func (n: Int) -> Bool { |
||
if(n % 3 == 0) { |
if(n % 3 == 0) { |
||
printf("Fizz") |
printf("Fizz") |
||
Line 6,880: | Line 6,880: | ||
println() |
println() |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Order}}== |
=={{header|Order}}== |
||
< |
<syntaxhighlight lang="c">#include <order/interpreter.h> |
||
// Get FB for one number |
// Get FB for one number |
||
Line 6,901: | Line 6,901: | ||
ORDER_PP( // foreach instead of map, to print but return nothing |
ORDER_PP( // foreach instead of map, to print but return nothing |
||
8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100)) |
8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100)) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {FizzBuzz X} |
fun {FizzBuzz X} |
||
if X mod 15 == 0 then 'FizzBuzz' |
if X mod 15 == 0 then 'FizzBuzz' |
||
Line 6,915: | Line 6,915: | ||
for I in 1..100 do |
for I in 1..100 do |
||
{Show {FizzBuzz I}} |
{Show {FizzBuzz I}} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">{for(n=1,100, |
||
print(if(n%3, |
print(if(n%3, |
||
if(n%5, |
if(n%5, |
||
Line 6,932: | Line 6,932: | ||
) |
) |
||
)) |
)) |
||
)}</ |
)}</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">program fizzbuzz(output); |
||
var |
var |
||
i: integer; |
i: integer; |
||
Line 6,948: | Line 6,948: | ||
else |
else |
||
writeln(i) |
writeln(i) |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|PDP-8 Assembly}}== |
=={{header|PDP-8 Assembly}}== |
||
Line 6,955: | Line 6,955: | ||
Runs on SimH, or any PDP-8 with an EAE |
Runs on SimH, or any PDP-8 with an EAE |
||
< |
<syntaxhighlight lang="assembly"> |
||
/-------------------------------------------------------- |
/-------------------------------------------------------- |
||
/THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL). |
/THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL). |
||
Line 7,089: | Line 7,089: | ||
CR; LF; EOT |
CR; LF; EOT |
||
$ |
$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 7,207: | Line 7,207: | ||
=={{header|Peloton}}== |
=={{header|Peloton}}== |
||
Variable-length padded English dialect |
Variable-length padded English dialect |
||
< |
<syntaxhighlight lang="sgml"><# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE> |
||
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#> |
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#> |
||
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#> |
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#> |
||
Line 7,215: | Line 7,215: | ||
<# NEITHER><# SAY PARAMETER>1</#></#> |
<# NEITHER><# SAY PARAMETER>1</#></#> |
||
</#></#> |
</#></#> |
||
<# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#></ |
<# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#></syntaxhighlight> |
||
Fixed-length English dialect |
Fixed-length English dialect |
||
< |
<syntaxhighlight lang="sgml"><@ DEFUDRLIT>__FizzBuzz|<@ SAW> |
||
<@ TSTMD0PARLIT>1|3</@> |
<@ TSTMD0PARLIT>1|3</@> |
||
<@ TSTMD0PARLIT>1|5</@> |
<@ TSTMD0PARLIT>1|5</@> |
||
Line 7,225: | Line 7,225: | ||
<@ NTH><@ SAYPAR>1</@></@> |
<@ NTH><@ SAYPAR>1</@></@> |
||
</@></@> |
</@></@> |
||
<@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|...</@> </@></ |
<@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|...</@> </@></syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl"> |
||
use strict; |
use strict; |
||
use warnings; |
use warnings; |
||
Line 7,238: | Line 7,238: | ||
: $i % 5 == 0 ? "Buzz" |
: $i % 5 == 0 ? "Buzz" |
||
: $i; |
: $i; |
||
}</ |
}</syntaxhighlight> |
||
More concisely: |
More concisely: |
||
< |
<syntaxhighlight lang="perl">print 'Fizz'x!($_ % 3) . 'Buzz'x!($_ % 5) || $_, "\n" for 1 .. 100;</syntaxhighlight> |
||
For code-golfing: |
For code-golfing: |
||
< |
<syntaxhighlight lang="perl">print+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..1e2</syntaxhighlight> |
||
For array of values: |
For array of values: |
||
< |
<syntaxhighlight lang="perl">map((Fizz)[$_%3].(Buzz)[$_%5]||$_,1..100);</syntaxhighlight> |
||
Cheating: |
Cheating: |
||
< |
<syntaxhighlight lang="perl"> |
||
use feature "say"; |
use feature "say"; |
||
@a = ("FizzBuzz", 0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz"); |
@a = ("FizzBuzz", 0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz"); |
||
say $a[$_ % 15] || $_ for 1..100;</ |
say $a[$_ % 15] || $_ for 1..100;</syntaxhighlight> |
||
as a subroutine: |
as a subroutine: |
||
< |
<syntaxhighlight lang="perl"> |
||
sub fizz_buzz { |
sub fizz_buzz { |
||
join("\n", map { |
join("\n", map { |
||
Line 7,275: | Line 7,275: | ||
} |
} |
||
print fizz_buzz; |
print fizz_buzz; |
||
</syntaxhighlight> |
|||
</lang> |
|||
By transforming a list: |
By transforming a list: |
||
< |
<syntaxhighlight lang="perl"> |
||
@FB1 = (1..100); |
@FB1 = (1..100); |
||
@FB2 = map{!($_%3 or $_%5)?'FizzBuzz': $_}@FB1; |
@FB2 = map{!($_%3 or $_%5)?'FizzBuzz': $_}@FB1; |
||
Line 7,286: | Line 7,286: | ||
@FB5 = map{$_."\n"}@FB4; |
@FB5 = map{$_."\n"}@FB4; |
||
print @FB5; |
print @FB5; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
{{libheader|Phix/basics}} |
||
{{trans|C}} |
{{trans|C}} |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #008000;">"%d\n"<span style="color: #0000FF;">,<span style="color: #008000;">"Fizz\n"<span style="color: #0000FF;">,<span style="color: #008000;">"Buzz\n"<span style="color: #0000FF;">,<span style="color: #008000;">"FizzBuzz\n"<span style="color: #0000FF;">}</span> |
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #008000;">"%d\n"<span style="color: #0000FF;">,<span style="color: #008000;">"Fizz\n"<span style="color: #0000FF;">,<span style="color: #008000;">"Buzz\n"<span style="color: #0000FF;">,<span style="color: #008000;">"FizzBuzz\n"<span style="color: #0000FF;">}</span> |
||
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span> |
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span> |
||
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #000000;">x<span style="color: #0000FF;">[<span style="color: #000000;">1<span style="color: #0000FF;">+<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">2<span style="color: #0000FF;">*<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">]<span style="color: #0000FF;">,<span style="color: #000000;">i<span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #000000;">x<span style="color: #0000FF;">[<span style="color: #000000;">1<span style="color: #0000FF;">+<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">2<span style="color: #0000FF;">*<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">]<span style="color: #0000FF;">,<span style="color: #000000;">i<span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">for |
<span style="color: #008080;">end</span> <span style="color: #008080;">for |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
Two variants with tabulated output: |
Two variants with tabulated output: |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">f<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">i<span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">f<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">i<span style="color: #0000FF;">)</span> |
||
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1<span style="color: #0000FF;">+<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">2<span style="color: #0000FF;">*<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)</span> |
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1<span style="color: #0000FF;">+<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">2<span style="color: #0000FF;">*<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)</span> |
||
Line 7,304: | Line 7,304: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #7060A8;">join_by<span style="color: #0000FF;">(<span style="color: #7060A8;">apply<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">f<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">) |
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #7060A8;">join_by<span style="color: #0000FF;">(<span style="color: #7060A8;">apply<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">f<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
(output same as below) |
(output same as below) |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply<span style="color: #0000FF;">(<span style="color: #004600;">true<span style="color: #0000FF;">,<span style="color: #7060A8;">sprintf<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #008000;">"%-8d"<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">)<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply<span style="color: #0000FF;">(<span style="color: #004600;">true<span style="color: #0000FF;">,<span style="color: #7060A8;">sprintf<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #008000;">"%-8d"<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">)<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Fizz "</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Fizz "</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
Line 7,312: | Line 7,312: | ||
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">15</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">15</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"FizzBuzz"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">15</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">15</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"FizzBuzz"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #7060A8;">join_by<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">) |
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #7060A8;">join_by<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">) |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 7,327: | Line 7,327: | ||
</pre> |
</pre> |
||
Grotesquely inefficient (non-tabulated output), just for fun. Can you do worse, yet keep it semi-plausibile that someone might have actually earnestly written it? |
Grotesquely inefficient (non-tabulated output), just for fun. Can you do worse, yet keep it semi-plausibile that someone might have actually earnestly written it? |
||
<!--< |
<!--<syntaxhighlight lang="phix">--> |
||
<span style="color: #008080;">constant</span> <span style="color: #000000;">threes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
<span style="color: #008080;">constant</span> <span style="color: #000000;">threes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
||
<span style="color: #000000;">fives</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
<span style="color: #000000;">fives</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span> |
||
Line 7,347: | Line 7,347: | ||
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"\n"<span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"\n"<span style="color: #0000FF;">)</span> |
||
<span style="color: #008080;">end</span> <span style="color: #008080;">for |
<span style="color: #008080;">end</span> <span style="color: #008080;">for |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|PHL}}== |
=={{header|PHL}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="phl">module fizzbuzz; |
||
extern printf; |
extern printf; |
||
Line 7,372: | Line 7,372: | ||
return 0; |
return 0; |
||
]</ |
]</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
===if/else ladder approach=== |
===if/else ladder approach=== |
||
< |
<syntaxhighlight lang="php"><?php |
||
for ($i = 1; $i <= 100; $i++) |
for ($i = 1; $i <= 100; $i++) |
||
{ |
{ |
||
Line 7,388: | Line 7,388: | ||
echo "$i\n"; |
echo "$i\n"; |
||
} |
} |
||
?></ |
?></syntaxhighlight> |
||
===Concatenation approach=== |
===Concatenation approach=== |
||
Uses PHP's concatenation operator (.=) to build the output string. The concatenation operator allows us to add data to the end of a string without overwriting the whole string. Since Buzz will always appear if our number is divisible by five, and Buzz is the second part of "FizzBuzz", we can simply append "Buzz" to our string. |
Uses PHP's concatenation operator (.=) to build the output string. The concatenation operator allows us to add data to the end of a string without overwriting the whole string. Since Buzz will always appear if our number is divisible by five, and Buzz is the second part of "FizzBuzz", we can simply append "Buzz" to our string. |
||
In contrast to the if-else ladder, this method lets us skip the check to see if $i is divisible by both 3 and 5 (i.e. 15). However, we get the added complexity of needing to reset $str to an empty string (not necessary in some other languages), and we also need a separate if statement to check to see if our string is empty, so we know if $i was not divisible by 3 or 5. |
In contrast to the if-else ladder, this method lets us skip the check to see if $i is divisible by both 3 and 5 (i.e. 15). However, we get the added complexity of needing to reset $str to an empty string (not necessary in some other languages), and we also need a separate if statement to check to see if our string is empty, so we know if $i was not divisible by 3 or 5. |
||
< |
<syntaxhighlight lang="php"><?php |
||
for ( $i = 1; $i <= 100; ++$i ) |
for ( $i = 1; $i <= 100; ++$i ) |
||
{ |
{ |
||
Line 7,409: | Line 7,409: | ||
echo $str . "\n"; |
echo $str . "\n"; |
||
} |
} |
||
?></ |
?></syntaxhighlight> |
||
===Concatenation approach without if-s=== |
===Concatenation approach without if-s=== |
||
< |
<syntaxhighlight lang="php"><?php |
||
for ( |
for ( |
||
$i = 0; |
$i = 0; |
||
Line 7,418: | Line 7,418: | ||
) |
) |
||
echo $o ? : $i, PHP_EOL; |
echo $o ? : $i, PHP_EOL; |
||
?></ |
?></syntaxhighlight> |
||
===One Liner Approach=== |
===One Liner Approach=== |
||
< |
<syntaxhighlight lang="php"><?php |
||
for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i); |
for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i); |
||
?></ |
?></syntaxhighlight> |
||
===Compact One Liner Approach=== |
===Compact One Liner Approach=== |
||
< |
<syntaxhighlight lang="php">for($i=0;$i++<100;)echo($i%3?'':'Fizz').($i%5?'':'Buzz')?:$i,"\n";</syntaxhighlight> |
||
===Array One Liner Approach=== |
===Array One Liner Approach=== |
||
< |
<syntaxhighlight lang="php">for($i = 0; $i++ < 100;) echo [$i, 'Fizz', 'Buzz', 'FizzBuzz'][!($i % 3) + 2 * !($i % 5)], "\n";</syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
Line 7,436: | Line 7,436: | ||
===Using a map=== |
===Using a map=== |
||
< |
<syntaxhighlight lang="picat">fizzbuzz_map => |
||
println(fizzbuzz_map), |
println(fizzbuzz_map), |
||
FB = [I : I in 1..100], |
FB = [I : I in 1..100], |
||
Line 7,445: | Line 7,445: | ||
end |
end |
||
end, |
end, |
||
println(FB).</ |
println(FB).</syntaxhighlight> |
||
===Using a template for the pattern=== |
===Using a template for the pattern=== |
||
< |
<syntaxhighlight lang="picat">fizzbuzz_template1 => |
||
println(fizzbuzz_template1), |
println(fizzbuzz_template1), |
||
N = 100, |
N = 100, |
||
Line 7,457: | Line 7,457: | ||
print(" ") |
print(" ") |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
===Another version with templates=== |
===Another version with templates=== |
||
< |
<syntaxhighlight lang="picat">fizzbuzz_template2 => |
||
println(fizzbuzz_template2), |
println(fizzbuzz_template2), |
||
N = 100, |
N = 100, |
||
Line 7,472: | Line 7,472: | ||
printf("%w ", cond(var(F[I]),I, F[I])) |
printf("%w ", cond(var(F[I]),I, F[I])) |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
Below are some versions for identifying the FizzBuzziness of a number. |
Below are some versions for identifying the FizzBuzziness of a number. |
||
To be used with the following general wrapper: |
To be used with the following general wrapper: |
||
< |
<syntaxhighlight lang="picat">fizzbuzz(Goal) => |
||
println(Goal), |
println(Goal), |
||
foreach(I in 1..100) |
foreach(I in 1..100) |
||
printf("%w ", apply(Goal,I)) |
printf("%w ", apply(Goal,I)) |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
===Plain imperative approach: if/else=== |
===Plain imperative approach: if/else=== |
||
< |
<syntaxhighlight lang="picat">fb1(I) = V => |
||
V = I.to_string(), |
V = I.to_string(), |
||
if I mod 15 == 0 then V := "FizzBuzz" |
if I mod 15 == 0 then V := "FizzBuzz" |
||
elseif I mod 3 == 0 then V := "Fizz" |
elseif I mod 3 == 0 then V := "Fizz" |
||
elseif I mod 5 == 0 then V := "Buzz" |
elseif I mod 5 == 0 then V := "Buzz" |
||
end.</ |
end.</syntaxhighlight> |
||
===Pattern matching + conditions in head=== |
===Pattern matching + conditions in head=== |
||
< |
<syntaxhighlight lang="picat">fb2(I) = "FizzBuzz", I mod 15 == 0 => true. |
||
fb2(I) = "Fizz", I mod 3 == 0 => true. |
fb2(I) = "Fizz", I mod 3 == 0 => true. |
||
fb2(I) = "Buzz", I mod 5 == 0 => true. |
fb2(I) = "Buzz", I mod 5 == 0 => true. |
||
fb2(I) = I.to_string() => true.</ |
fb2(I) = I.to_string() => true.</syntaxhighlight> |
||
===Another pattern matching approach=== |
===Another pattern matching approach=== |
||
< |
<syntaxhighlight lang="picat">fb3(I) = fb3b(I, I mod 3, I mod 5). |
||
fb3b(_I,0,0) = "FizzBuzz". |
fb3b(_I,0,0) = "FizzBuzz". |
||
fb3b(_I,_,0) = "Buzz". |
fb3b(_I,_,0) = "Buzz". |
||
fb3b(_I,0,_) = "Fizz". |
fb3b(_I,0,_) = "Fizz". |
||
fb3b(I,_,_) = I.</ |
fb3b(I,_,_) = I.</syntaxhighlight> |
||
===Using cond/3 and string concatenation=== |
===Using cond/3 and string concatenation=== |
||
< |
<syntaxhighlight lang="picat">fb4(I) = cond(I mod 3 == 0, "Fizz", "") ++ |
||
cond(I mod 5 == 0, "Buzz", "") ++ |
cond(I mod 5 == 0, "Buzz", "") ++ |
||
cond(not ((I mod 3 == 0; I mod 5==0)), I.to_string(), "").</ |
cond(not ((I mod 3 == 0; I mod 5==0)), I.to_string(), "").</syntaxhighlight> |
||
===Recursive function (conditions in head)=== |
===Recursive function (conditions in head)=== |
||
< |
<syntaxhighlight lang="picat">fizzbuzz_rec => |
||
print(fizzbuzz_rec), |
print(fizzbuzz_rec), |
||
fb5(100,[],L), |
fb5(100,[],L), |
||
Line 7,525: | Line 7,525: | ||
fb5(N-1,L1 ++ ["Fizz"], L). |
fb5(N-1,L1 ++ ["Fizz"], L). |
||
fb5(N,L1,L), N mod 3 > 0, N mod 5 > 0 => |
fb5(N,L1,L), N mod 3 > 0, N mod 5 > 0 => |
||
fb5(N-1,L1 ++ [N.to_string()], L).</ |
fb5(N-1,L1 ++ [N.to_string()], L).</syntaxhighlight> |
||
===Golfing style=== |
===Golfing style=== |
||
< |
<syntaxhighlight lang="picat">fizzbuzz_golf => |
||
println(fizzbuzz_golf), |
println(fizzbuzz_golf), |
||
[cond(P=="",I,P):I in 1..100,(I mod 3==0->P="Fizz";P=""),(I mod 5==0->P:=P++"Buzz";true)].println(). |
[cond(P=="",I,P):I in 1..100,(I mod 3==0->P="Fizz";P=""),(I mod 5==0->P:=P++"Buzz";true)].println(). |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Planner version=== |
===Planner version=== |
||
Picat has support for "classic" planning problems. The <code>planner</code> module must be imported. |
Picat has support for "classic" planning problems. The <code>planner</code> module must be imported. |
||
< |
<syntaxhighlight lang="picat">import planner. |
||
fizzbuzz_planner => |
fizzbuzz_planner => |
||
println(fizzbuzz_planner), |
println(fizzbuzz_planner), |
||
Line 7,567: | Line 7,567: | ||
Move = H.to_string(), |
Move = H.to_string(), |
||
To = H-1, |
To = H-1, |
||
Cost = 1.</ |
Cost = 1.</syntaxhighlight> |
||
Here we test everything. |
Here we test everything. |
||
< |
<syntaxhighlight lang="picat">go => |
||
fizzbuzz_map, |
fizzbuzz_map, |
||
fizzbuzz_template1, |
fizzbuzz_template1, |
||
Line 7,583: | Line 7,583: | ||
call(fizzbuzz,FB) |
call(fizzbuzz,FB) |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
We could simply use '[http://software-lab.de/doc/refA.html#at at]' here: |
We could simply use '[http://software-lab.de/doc/refA.html#at at]' here: |
||
< |
<syntaxhighlight lang="picolisp">(for N 100 |
||
(prinl |
(prinl |
||
(or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) ) |
(or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) ) |
||
Line 7,594: | Line 7,594: | ||
# Rest of the times 'N' is printed as it loops in 'for'. |
# Rest of the times 'N' is printed as it loops in 'for'. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or do it the standard way: |
Or do it the standard way: |
||
< |
<syntaxhighlight lang="picolisp">(for N 100 |
||
(prinl |
(prinl |
||
(cond |
(cond |
||
Line 7,602: | Line 7,602: | ||
((=0 (% N 3)) "Fizz") |
((=0 (% N 3)) "Fizz") |
||
((=0 (% N 5)) "Buzz") |
((=0 (% N 5)) "Buzz") |
||
(T N) ) ) )</ |
(T N) ) ) )</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">int main(){ |
||
for(int i = 1; i <= 100; i++) { |
for(int i = 1; i <= 100; i++) { |
||
if(i % 15 == 0) { |
if(i % 15 == 0) { |
||
Line 7,617: | Line 7,617: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PILOT}}== |
=={{header|PILOT}}== |
||
< |
<syntaxhighlight lang="pilot">C :i = 0 |
||
*loop |
*loop |
||
C :i = i + 1 |
C :i = i + 1 |
||
Line 7,642: | Line 7,642: | ||
J : *loop |
J : *loop |
||
*finished |
*finished |
||
END:</ |
END:</syntaxhighlight> |
||
=={{header|PIR}}== |
=={{header|PIR}}== |
||
{{works with|Parrot|tested with 2.4.0}} |
{{works with|Parrot|tested with 2.4.0}} |
||
< |
<syntaxhighlight lang="pir">.sub main :main |
||
.local int f |
.local int f |
||
.local int mf |
.local int mf |
||
Line 7,679: | Line 7,679: | ||
DONE: |
DONE: |
||
end |
end |
||
.end</ |
.end</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pl/i">do i = 1 to 100; |
||
select; |
select; |
||
when (mod(i,15) = 0) put skip list ('FizzBuzz'); |
when (mod(i,15) = 0) put skip list ('FizzBuzz'); |
||
Line 7,689: | Line 7,689: | ||
otherwise put skip list (i); |
otherwise put skip list (i); |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|PL/M}}== |
=={{header|PL/M}}== |
||
< |
<syntaxhighlight lang="plm">100H: |
||
/* DECLARE OUTPUT IN TERMS OF CP/M - |
/* DECLARE OUTPUT IN TERMS OF CP/M - |
||
Line 7,736: | Line 7,736: | ||
/* EXIT TO CP/M */ |
/* EXIT TO CP/M */ |
||
CALL BDOS(0,0); |
CALL BDOS(0,0); |
||
EOF</ |
EOF</syntaxhighlight> |
||
=={{header|PL/SQL}}== |
=={{header|PL/SQL}}== |
||
< |
<syntaxhighlight lang="plsql">begin |
||
for i in 1 .. 100 |
for i in 1 .. 100 |
||
loop |
loop |
||
Line 7,753: | Line 7,753: | ||
end case; |
end case; |
||
end loop; |
end loop; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Pony}}== |
=={{header|Pony}}== |
||
< |
<syntaxhighlight lang="pony">use "collections" |
||
actor Main |
actor Main |
||
Line 7,773: | Line 7,773: | ||
else |
else |
||
n.string() |
n.string() |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang="pop11">lvars str; |
||
for i from 1 to 100 do |
for i from 1 to 100 do |
||
if i rem 15 = 0 then |
if i rem 15 = 0 then |
||
Line 7,788: | Line 7,788: | ||
endif; |
endif; |
||
printf(str, '%s\n'); |
printf(str, '%s\n'); |
||
endfor;</ |
endfor;</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
< |
<syntaxhighlight lang="postscript">1 1 100 { |
||
/c false def |
/c false def |
||
dup 3 mod 0 eq { (Fizz) print /c true def } if |
dup 3 mod 0 eq { (Fizz) print /c true def } if |
||
Line 7,797: | Line 7,797: | ||
c {pop}{( ) cvs print} ifelse |
c {pop}{( ) cvs print} ifelse |
||
(\n) print |
(\n) print |
||
} for</ |
} for</syntaxhighlight> |
||
or... |
or... |
||
< |
<syntaxhighlight lang="postscript">/fizzdict 100 dict def |
||
fizzdict begin |
fizzdict begin |
||
/notmod{ ( ) cvs } def |
/notmod{ ( ) cvs } def |
||
Line 7,809: | Line 7,809: | ||
1 1 100 { mod15} for |
1 1 100 { mod15} for |
||
1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for |
1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Potion}}== |
=={{header|Potion}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
1 to 100 (a): |
1 to 100 (a): |
||
if (a % 15 == 0): |
if (a % 15 == 0): |
||
Line 7,821: | Line 7,821: | ||
'Buzz'. |
'Buzz'. |
||
else: a. string print |
else: a. string print |
||
"\n" print.</ |
"\n" print.</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
===Straightforward, looping=== |
===Straightforward, looping=== |
||
< |
<syntaxhighlight lang="powershell">for ($i = 1; $i -le 100; $i++) { |
||
if ($i % 15 -eq 0) { |
if ($i % 15 -eq 0) { |
||
"FizzBuzz" |
"FizzBuzz" |
||
Line 7,835: | Line 7,835: | ||
$i |
$i |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Pipeline, Switch=== |
===Pipeline, Switch=== |
||
< |
<syntaxhighlight lang="powershell">$txt=$null |
||
1..100 | ForEach-Object { |
1..100 | ForEach-Object { |
||
switch ($_) { |
switch ($_) { |
||
Line 7,844: | Line 7,844: | ||
$_ { if($txt) { $txt } else { $_ }; $txt=$null } |
$_ { if($txt) { $txt } else { $_ }; $txt=$null } |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Concatenation=== |
===Concatenation=== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="powershell">1..100 | ForEach-Object { |
||
$s = '' |
$s = '' |
||
if ($_ % 3 -eq 0) { $s += "Fizz" } |
if ($_ % 3 -eq 0) { $s += "Fizz" } |
||
Line 7,854: | Line 7,854: | ||
if (-not $s) { $s = $_ } |
if (-not $s) { $s = $_ } |
||
$s |
$s |
||
}</ |
}</syntaxhighlight> |
||
===Piping, Evaluation, Concatenation=== |
===Piping, Evaluation, Concatenation=== |
||
< |
<syntaxhighlight lang="powershell"> |
||
1..100 | % {write-host("$(if(($_ % 3 -ne 0) -and ($_ % 5 -ne 0)){$_})$(if($_ % 3 -eq 0){"Fizz"})$(if($_ % 5 -eq 0){"Buzz"})")} |
1..100 | % {write-host("$(if(($_ % 3 -ne 0) -and ($_ % 5 -ne 0)){$_})$(if($_ % 3 -eq 0){"Fizz"})$(if($_ % 5 -eq 0){"Buzz"})")} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Filter, Piping, Regex Matching, Array Auto-Selection=== |
===Filter, Piping, Regex Matching, Array Auto-Selection=== |
||
< |
<syntaxhighlight lang="powershell"> |
||
filter fizz-buzz{ |
filter fizz-buzz{ |
||
@( |
@( |
||
Line 7,877: | Line 7,877: | ||
1..100 | fizz-buzz |
1..100 | fizz-buzz |
||
</syntaxhighlight> |
|||
</lang> |
|||
===String Manipulation with Regex=== |
===String Manipulation with Regex=== |
||
< |
<syntaxhighlight lang="powershell"> |
||
(1..100 -join "`n") + "`nFizzBuzz" -replace '(?ms)(^([369]([369]|(?=0|$))|[258][147]|[147]([28]|(?=5))))(?=[05]?$.*(Fizz))|(((?<=[369])|[^369])0+|((?<=[147\s])|[^147\s])5)(?=$.*(Buzz))|FizzBuzz', '$5$9' |
(1..100 -join "`n") + "`nFizzBuzz" -replace '(?ms)(^([369]([369]|(?=0|$))|[258][147]|[147]([28]|(?=5))))(?=[05]?$.*(Fizz))|(((?<=[369])|[^369])0+|((?<=[147\s])|[^147\s])5)(?=$.*(Buzz))|FizzBuzz', '$5$9' |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
Line 7,888: | Line 7,888: | ||
Reserved variable "width" in Processing is 100 pixels by default, suitable for this FizzBuzz exercise. |
Reserved variable "width" in Processing is 100 pixels by default, suitable for this FizzBuzz exercise. |
||
Accordingly, range is pixel index from 0 to 99. |
Accordingly, range is pixel index from 0 to 99. |
||
< |
<syntaxhighlight lang="processing">for (int i = 0; i < width; i++) { |
||
if (i % 3 == 0 && i % 5 == 0) { |
if (i % 3 == 0 && i % 5 == 0) { |
||
stroke(255, 255, 0); |
stroke(255, 255, 0); |
||
Line 7,906: | Line 7,906: | ||
} |
} |
||
line(i, 0, i, height); |
line(i, 0, i, height); |
||
}</ |
}</syntaxhighlight> |
||
===Console & Visualization, Ternary=== |
===Console & Visualization, Ternary=== |
||
< |
<syntaxhighlight lang="processing">for (int i = 0; i < width; i++) { |
||
stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF); |
stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF); |
||
line(i, 0, i, height); |
line(i, 0, i, height); |
||
println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i); |
println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i); |
||
}</ |
}</syntaxhighlight> |
||
===Console=== |
===Console=== |
||
< |
<syntaxhighlight lang="processing">for (int i = 1; i <= 100; i++) { |
||
if (i % 3 == 0) { |
if (i % 3 == 0) { |
||
print("Fizz"); |
print("Fizz"); |
||
Line 7,925: | Line 7,925: | ||
} |
} |
||
print("\n"); |
print("\n"); |
||
}</ |
}</syntaxhighlight> |
||
===Console, "Futureproof"=== |
===Console, "Futureproof"=== |
||
< |
<syntaxhighlight lang="processing">for(int i = 1; i <= 100; i++){ |
||
String output = ""; |
String output = ""; |
||
Line 7,936: | Line 7,936: | ||
if(output == "") output = str(i); |
if(output == "") output = str(i); |
||
println(output); |
println(output); |
||
}</ |
}</syntaxhighlight> |
||
All examples produce the same console output: |
All examples produce the same console output: |
||
Line 8,047: | Line 8,047: | ||
{{works with|SWI Prolog|4.8.0}} |
{{works with|SWI Prolog|4.8.0}} |
||
Maybe not the most conventional way to write this in Prolog. The fizzbuzz predicate uses a higher-order predicate and print_item uses the if-then-else construction. |
Maybe not the most conventional way to write this in Prolog. The fizzbuzz predicate uses a higher-order predicate and print_item uses the if-then-else construction. |
||
< |
<syntaxhighlight lang="prolog">fizzbuzz :- |
||
foreach(between(1, 100, X), print_item(X)). |
foreach(between(1, 100, X), print_item(X)). |
||
Line 8,059: | Line 8,059: | ||
; print(X) |
; print(X) |
||
), |
), |
||
nl.</ |
nl.</syntaxhighlight> |
||
More conventional: |
More conventional: |
||
< |
<syntaxhighlight lang="prolog">fizzbuzz(X) :- 0 is X mod 15, write('FizzBuzz'). |
||
fizzbuzz(X) :- 0 is X mod 3, write('Fizz'). |
fizzbuzz(X) :- 0 is X mod 3, write('Fizz'). |
||
fizzbuzz(X) :- 0 is X mod 5, write('Buzz'). |
fizzbuzz(X) :- 0 is X mod 5, write('Buzz'). |
||
fizzbuzz(X) :- write(X). |
fizzbuzz(X) :- write(X). |
||
dofizzbuzz :- foreach(between(1, 100, X), (fizzbuzz(X),nl)).</ |
dofizzbuzz :- foreach(between(1, 100, X), (fizzbuzz(X),nl)).</syntaxhighlight> |
||
Clearer: |
Clearer: |
||
< |
<syntaxhighlight lang="prolog">% N /3? /5? V |
||
fizzbuzz(_, yes, yes, 'FizzBuzz'). |
fizzbuzz(_, yes, yes, 'FizzBuzz'). |
||
fizzbuzz(_, yes, no, 'Fizz'). |
fizzbuzz(_, yes, no, 'Fizz'). |
||
Line 8,087: | Line 8,087: | ||
main :- |
main :- |
||
foreach(between(1,100, N), fizz_buzz_or_n(N)).</ |
foreach(between(1,100, N), fizz_buzz_or_n(N)).</syntaxhighlight> |
||
Using modern Prolog techniques, resulting in idiomatic, highly declarative code: |
Using modern Prolog techniques, resulting in idiomatic, highly declarative code: |
||
{{works with|SWI Prolog|8.2.1}} {{works with|Scryer Prolog|0.7.8}} |
{{works with|SWI Prolog|8.2.1}} {{works with|Scryer Prolog|0.7.8}} |
||
< |
<syntaxhighlight lang="prolog"> |
||
% This implementation uses modern Prolog techniques |
% This implementation uses modern Prolog techniques |
||
% in order to be an idiomatic solution that uses logical purity, generality and determinism wherever possible: |
% in order to be an idiomatic solution that uses logical purity, generality and determinism wherever possible: |
||
Line 8,160: | Line 8,160: | ||
eq_t(>, false). |
eq_t(>, false). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Line 8,166: | Line 8,166: | ||
=={{header|Pyret}}== |
=={{header|Pyret}}== |
||
< |
<syntaxhighlight lang="pyret">fun fizzbuzz(n :: NumPositive) -> String: |
||
doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'. |
doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'. |
||
For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.``` |
For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.``` |
||
Line 8,183: | Line 8,183: | ||
end |
end |
||
range(1, 101).map(fizzbuzz).each(print)</ |
range(1, 101).map(fizzbuzz).each(print)</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Python2: Simple=== |
===Python2: Simple=== |
||
< |
<syntaxhighlight lang="python">for i in xrange(1, 101): |
||
if i % 15 == 0: |
if i % 15 == 0: |
||
print "FizzBuzz" |
print "FizzBuzz" |
||
Line 8,195: | Line 8,195: | ||
print "Buzz" |
print "Buzz" |
||
else: |
else: |
||
print i</ |
print i</syntaxhighlight> |
||
===Python3: Simple=== |
===Python3: Simple=== |
||
< |
<syntaxhighlight lang="python">for i in range(1, 101): |
||
if i % 15 == 0: |
if i % 15 == 0: |
||
print("FizzBuzz") |
print("FizzBuzz") |
||
Line 8,206: | Line 8,206: | ||
print("Buzz") |
print("Buzz") |
||
else: |
else: |
||
print(i)</ |
print(i)</syntaxhighlight> |
||
===Python: Simple - no duplication === |
===Python: Simple - no duplication === |
||
< |
<syntaxhighlight lang="python">for n in range(1,101): |
||
response = '' |
response = '' |
||
Line 8,218: | Line 8,218: | ||
print(response or n) |
print(response or n) |
||
</syntaxhighlight> |
|||
</lang> |
|||
One liner using string concatenation: |
One liner using string concatenation: |
||
< |
<syntaxhighlight lang="python">for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i)</syntaxhighlight> |
||
One liner another code: |
One liner another code: |
||
< |
<syntaxhighlight lang="python">for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)</syntaxhighlight> |
||
List Comprehensions: |
List Comprehensions: |
||
< |
<syntaxhighlight lang="python"> |
||
for n in range(1, 100): |
for n in range(1, 100): |
||
fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ]) |
fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ]) |
||
print fb if fb else n |
print fb if fb else n |
||
</syntaxhighlight> |
|||
</lang> |
|||
Another list comprehension: |
Another list comprehension: |
||
< |
<syntaxhighlight lang="python"> |
||
print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)])) |
print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)])) |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Python: List Comprehension (Python 3)=== |
===Python: List Comprehension (Python 3)=== |
||
< |
<syntaxhighlight lang="python">[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)]</syntaxhighlight> |
||
===Python: Lazily=== |
===Python: Lazily=== |
||
You can also create a lazy, unbounded sequence by using generator expressions: |
You can also create a lazy, unbounded sequence by using generator expressions: |
||
< |
<syntaxhighlight lang="python">from itertools import cycle, izip, count, islice |
||
fizzes = cycle([""] * 2 + ["Fizz"]) |
fizzes = cycle([""] * 2 + ["Fizz"]) |
||
Line 8,253: | Line 8,253: | ||
# print the first 100 |
# print the first 100 |
||
for i in islice(fizzbuzz, 100): |
for i in islice(fizzbuzz, 100): |
||
print i</ |
print i</syntaxhighlight> |
||
Or equivalently, in terms of map, and Python 3 libraries: |
Or equivalently, in terms of map, and Python 3 libraries: |
||
{{Works with|Python|3.7}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Fizz buzz''' |
||
from itertools import count, cycle, islice |
from itertools import count, cycle, islice |
||
Line 8,290: | Line 8,290: | ||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
===Python3.8: With walrus operator=== |
===Python3.8: With walrus operator=== |
||
< |
<syntaxhighlight lang="python">print(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i := n**4%-15) > -14 else n, range(1,100)))</syntaxhighlight> |
||
===Python: Math tricks=== |
===Python: Math tricks=== |
||
Numbers ending in 5 or 0 are divisible by 5. Numbers whose digits recursively summed to a single-digit number == 3,6 or 9 are divisible by 3. |
Numbers ending in 5 or 0 are divisible by 5. Numbers whose digits recursively summed to a single-digit number == 3,6 or 9 are divisible by 3. |
||
< |
<syntaxhighlight lang="python"> |
||
def numsum(n): |
def numsum(n): |
||
''' The recursive sum of all digits in a number |
''' The recursive sum of all digits in a number |
||
Line 8,311: | Line 8,311: | ||
or n |
or n |
||
print(response) |
print(response) |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Python3: Super concise: 1 line=== |
===Python3: Super concise: 1 line=== |
||
< |
<syntaxhighlight lang="python"> |
||
print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101))) |
print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Q}}== |
=={{header|Q}}== |
||
<syntaxhighlight lang="q"> |
|||
<lang Q> |
|||
q){(sum 1 2*0=x mod/:3 5)'[`$string x;`fizz;`buzz;`fizzbuzz]}1+til 20 |
q){(sum 1 2*0=x mod/:3 5)'[`$string x;`fizz;`buzz;`fizzbuzz]}1+til 20 |
||
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz</ |
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz</syntaxhighlight> |
||
https://code.kx.com/q/learn/reading/fizzbuzz/ |
https://code.kx.com/q/learn/reading/fizzbuzz/ |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
< |
<syntaxhighlight lang="qb64">For n = 1 To 100 |
||
If n Mod 15 = 0 Then |
If n Mod 15 = 0 Then |
||
Print "FizzBuzz" |
Print "FizzBuzz" |
||
Line 8,337: | Line 8,337: | ||
Print n |
Print n |
||
End If |
End If |
||
Next</ |
Next</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ times |
||
[ i^ 1+ |
[ i^ 1+ |
||
' echo |
' echo |
||
Line 8,354: | Line 8,354: | ||
say 'First 100 turns in the game of fizzbuzz:' cr cr |
say 'First 100 turns in the game of fizzbuzz:' cr cr |
||
100 fizzbuzz cr</ |
100 fizzbuzz cr</syntaxhighlight> |
||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="rsplus">xx <- x <- 1:100 |
||
xx[x %% 3 == 0] <- "Fizz" |
xx[x %% 3 == 0] <- "Fizz" |
||
xx[x %% 5 == 0] <- "Buzz" |
xx[x %% 5 == 0] <- "Buzz" |
||
xx[x %% 15 == 0] <- "FizzBuzz" |
xx[x %% 15 == 0] <- "FizzBuzz" |
||
xx</ |
xx</syntaxhighlight> |
||
Or, without directly checking for divisibility by 15: |
Or, without directly checking for divisibility by 15: |
||
< |
<syntaxhighlight lang="rsplus">xx <- rep("", 100) |
||
x <- 1:100 |
x <- 1:100 |
||
xx[x %% 3 == 0] <- paste0(xx[x %% 3 == 0], "Fizz") |
xx[x %% 3 == 0] <- paste0(xx[x %% 3 == 0], "Fizz") |
||
xx[x %% 5 == 0] <- paste0(xx[x %% 5 == 0], "Buzz") |
xx[x %% 5 == 0] <- paste0(xx[x %% 5 == 0], "Buzz") |
||
xx[xx == ""] <- x[xx == ""] |
xx[xx == ""] <- x[xx == ""] |
||
xx</ |
xx</syntaxhighlight> |
||
Or, (ab)using the vector recycling rule: |
Or, (ab)using the vector recycling rule: |
||
< |
<syntaxhighlight lang="rsplus">x <- paste0(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz")) |
||
cat(ifelse(x == "", 1:100, x), sep = "\n")</ |
cat(ifelse(x == "", 1:100, x), sep = "\n")</syntaxhighlight> |
||
Or, for an abuse of the recycling rules that could be generalised: |
Or, for an abuse of the recycling rules that could be generalised: |
||
< |
<syntaxhighlight lang="rsplus">x <- paste0(rep("", 100), rep(c("", "Fizz"), times = c(2, 1)), rep(c("", "Buzz"), times = c(4, 1))) |
||
cat(ifelse(x == "", 1:100, x), sep = "\n")</ |
cat(ifelse(x == "", 1:100, x), sep = "\n")</syntaxhighlight> |
||
Or, with a more straightforward use of ifelse: |
Or, with a more straightforward use of ifelse: |
||
< |
<syntaxhighlight lang="rsplus">x <- 1:100 |
||
ifelse(x %% 15 == 0, 'FizzBuzz', |
ifelse(x %% 15 == 0, 'FizzBuzz', |
||
ifelse(x %% 5 == 0, 'Buzz', |
ifelse(x %% 5 == 0, 'Buzz', |
||
ifelse(x %% 3 == 0, 'Fizz', x)))</ |
ifelse(x %% 3 == 0, 'Fizz', x)))</syntaxhighlight> |
||
Or, adapting from [https://rosettacode.org/wiki/General_FizzBuzz#Names_solution General FizzBuzz#Names solution]: |
Or, adapting from [https://rosettacode.org/wiki/General_FizzBuzz#Names_solution General FizzBuzz#Names solution]: |
||
< |
<syntaxhighlight lang="rsplus">namedNums <- c(Fizz = 3, Buzz = 5) |
||
for(i in 1:100) |
for(i in 1:100) |
||
{ |
{ |
||
isFactor <- i %% namedNums == 0 |
isFactor <- i %% namedNums == 0 |
||
print(if(any(isFactor)) paste0(names(namedNums)[isFactor], collapse = "") else i) |
print(if(any(isFactor)) paste0(names(namedNums)[isFactor], collapse = "") else i) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(for ([n (in-range 1 101)]) |
(for ([n (in-range 1 101)]) |
||
Line 8,402: | Line 8,402: | ||
[3 "fizz"] |
[3 "fizz"] |
||
[5 "buzz"] |
[5 "buzz"] |
||
[_ n])))</ |
[_ n])))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 8,408: | Line 8,408: | ||
{{works with|Rakudo Star|2015-09-10}} |
{{works with|Rakudo Star|2015-09-10}} |
||
Most straightforwardly: |
Most straightforwardly: |
||
<lang |
<syntaxhighlight lang="raku" line>for 1 .. 100 { |
||
when $_ %% (3 & 5) { say 'FizzBuzz'; } |
when $_ %% (3 & 5) { say 'FizzBuzz'; } |
||
when $_ %% 3 { say 'Fizz'; } |
when $_ %% 3 { say 'Fizz'; } |
||
when $_ %% 5 { say 'Buzz'; } |
when $_ %% 5 { say 'Buzz'; } |
||
default { .say; } |
default { .say; } |
||
}</ |
}</syntaxhighlight> |
||
Or abusing multi subs: |
Or abusing multi subs: |
||
<lang |
<syntaxhighlight lang="raku" line>multi sub fizzbuzz(Int $ where * %% 15) { 'FizzBuzz' } |
||
multi sub fizzbuzz(Int $ where * %% 5) { 'Buzz' } |
multi sub fizzbuzz(Int $ where * %% 5) { 'Buzz' } |
||
multi sub fizzbuzz(Int $ where * %% 3) { 'Fizz' } |
multi sub fizzbuzz(Int $ where * %% 3) { 'Fizz' } |
||
multi sub fizzbuzz(Int $number ) { $number } |
multi sub fizzbuzz(Int $number ) { $number } |
||
(1 .. 100)».&fizzbuzz.say;</ |
(1 .. 100)».&fizzbuzz.say;</syntaxhighlight> |
||
Or abusing list metaoperators: |
Or abusing list metaoperators: |
||
<lang |
<syntaxhighlight lang="raku" line>[1..100].map({[~] ($_%%3, $_%%5) »||» "" Z&& <fizz buzz> or $_ })».say</syntaxhighlight> |
||
Concisely (readable): |
Concisely (readable): |
||
<lang |
<syntaxhighlight lang="raku" line>say 'Fizz' x $_ %% 3 ~ 'Buzz' x $_ %% 5 || $_ for 1 .. 100;</syntaxhighlight> |
||
Shortest FizzBuzz to date: |
Shortest FizzBuzz to date: |
||
<lang |
<syntaxhighlight lang="raku" line>say "Fizz"x$_%%3~"Buzz"x$_%%5||$_ for 1..100</syntaxhighlight> |
||
And here's an implementation that never checks for divisibility: |
And here's an implementation that never checks for divisibility: |
||
<lang |
<syntaxhighlight lang="raku" line>.say for |
||
( |
( |
||
(flat ('' xx 2, 'Fizz') xx *) |
(flat ('' xx 2, 'Fizz') xx *) |
||
Line 8,434: | Line 8,434: | ||
) |
) |
||
Z|| |
Z|| |
||
1 .. 100;</ |
1 .. 100;</syntaxhighlight> |
||
=={{header|RapidQ}}== |
=={{header|RapidQ}}== |
||
The [[#BASIC|BASIC]] solutions work with RapidQ, too. |
The [[#BASIC|BASIC]] solutions work with RapidQ, too. |
||
However, here is a bit more esoteric solution using the IIF() function. |
However, here is a bit more esoteric solution using the IIF() function. |
||
< |
<syntaxhighlight lang="rapidq">FOR i=1 TO 100 |
||
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "") |
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "") |
||
PRINT IIF(LEN(t$), t$, i) |
PRINT IIF(LEN(t$), t$, i) |
||
NEXT i</ |
NEXT i</syntaxhighlight> |
||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
< |
<syntaxhighlight lang="rascal">import IO; |
||
public void fizzbuzz() { |
public void fizzbuzz() { |
||
Line 8,452: | Line 8,452: | ||
println((fb == "") ?"<n>" : fb); |
println((fb == "") ?"<n>" : fb); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">100 each 1 + as n |
||
'' |
'' |
||
n 3 mod 0 = if 'Fizz' cat |
n 3 mod 0 = if 'Fizz' cat |
||
n 5 mod 0 = if 'Buzz' cat |
n 5 mod 0 = if 'Buzz' cat |
||
dup empty if drop n |
dup empty if drop n |
||
say</ |
say</syntaxhighlight> |
||
=={{header|REALbasic}}== |
=={{header|REALbasic}}== |
||
Line 8,466: | Line 8,466: | ||
=={{header|ReasonML}}== |
=={{header|ReasonML}}== |
||
< |
<syntaxhighlight lang="ocaml"> |
||
let fizzbuzz i => |
let fizzbuzz i => |
||
switch (i mod 3, i mod 5) { |
switch (i mod 3, i mod 5) { |
||
Line 8,478: | Line 8,478: | ||
print_endline (fizzbuzz i) |
print_endline (fizzbuzz i) |
||
}; |
}; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
An implementation that concatenates strings and includes a proper code header (title, date, etc.) |
An implementation that concatenates strings and includes a proper code header (title, date, etc.) |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "FizzBuzz" |
Title: "FizzBuzz" |
||
URL: http://rosettacode.org/wiki/FizzBuzz |
URL: http://rosettacode.org/wiki/FizzBuzz |
||
Line 8,499: | Line 8,499: | ||
] |
] |
||
print x |
print x |
||
]</ |
]</syntaxhighlight> |
||
Here is an example by Nick Antonaccio. |
Here is an example by Nick Antonaccio. |
||
< |
<syntaxhighlight lang="rebol">repeat i 100 [ |
||
print switch/default 0 compose [ |
print switch/default 0 compose [ |
||
(mod i 15) ["fizzbuzz"] |
(mod i 15) ["fizzbuzz"] |
||
Line 8,507: | Line 8,507: | ||
(mod i 5) ["buzz"] |
(mod i 5) ["buzz"] |
||
][i] |
][i] |
||
]</ |
]</syntaxhighlight> |
||
And a minimized version: |
And a minimized version: |
||
< |
<syntaxhighlight lang="rebol">repeat i 100[j:""if i // 3 = 0[j:"fizz"]if i // 5 = 0[j: join j"buzz"]if""= j[j: i]print j]</syntaxhighlight> |
||
The following is presented as a curiosity only, not as an example of good coding practice: |
The following is presented as a curiosity only, not as an example of good coding practice: |
||
< |
<syntaxhighlight lang="rebol">m: func [i d] [0 = mod i d] |
||
spick: func [t x y][either any [not t "" = t][y][x]] |
spick: func [t x y][either any [not t "" = t][y][x]] |
||
zz: func [i] [rejoin [spick m i 3 "Fizz" "" spick m i 5 "Buzz" ""]] |
zz: func [i] [rejoin [spick m i 3 "Fizz" "" spick m i 5 "Buzz" ""]] |
||
repeat i 100 [print spick z: zz i z i]</ |
repeat i 100 [print spick z: zz i z i]</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="rebol">Red ["FizzBuzz"] |
||
repeat i 100 [ |
repeat i 100 [ |
||
Line 8,528: | Line 8,528: | ||
true [i] |
true [i] |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
This is a port of some [http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html Forth code]. |
This is a port of some [http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html Forth code]. |
||
< |
<syntaxhighlight lang="retro">: fizz? ( s-f ) 3 mod 0 = ; |
||
: buzz? ( s-f ) 5 mod 0 = ; |
: buzz? ( s-f ) 5 mod 0 = ; |
||
: num? ( s-f ) dup fizz? swap buzz? or 0 = ; |
: num? ( s-f ) dup fizz? swap buzz? or 0 = ; |
||
Line 8,539: | Line 8,539: | ||
: ?num ( s- ) num? &putn &drop if ; |
: ?num ( s- ) num? &putn &drop if ; |
||
: fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ; |
: fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ; |
||
: all ( - ) 100 [ 1+ fizzbuzz ] iter ;</ |
: all ( - ) 100 [ 1+ fizzbuzz ] iter ;</syntaxhighlight> |
||
It's cleaner to use quotes and combinators though: |
It's cleaner to use quotes and combinators though: |
||
< |
<syntaxhighlight lang="retro">needs math' |
||
: <fizzbuzz> |
: <fizzbuzz> |
||
[ 15 ^math'divisor? ] [ drop "FizzBuzz" puts ] when |
[ 15 ^math'divisor? ] [ drop "FizzBuzz" puts ] when |
||
[ 3 ^math'divisor? ] [ drop "Fizz" puts ] when |
[ 3 ^math'divisor? ] [ drop "Fizz" puts ] when |
||
[ 5 ^math'divisor? ] [ drop "Buzz" puts ] when putn ; |
[ 5 ^math'divisor? ] [ drop "Buzz" puts ] when putn ; |
||
: fizzbuzz cr 100 [ 1+ <fizzbuzz> space ] iter ;</ |
: fizzbuzz cr 100 [ 1+ <fizzbuzz> space ] iter ;</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 8,552: | Line 8,552: | ||
This version's program logic closely mirrors the problem statement: |
This version's program logic closely mirrors the problem statement: |
||
===three IF-THEN=== |
===three IF-THEN=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/ |
||
/*╔═══════════════════════════════════╗*/ |
/*╔═══════════════════════════════════╗*/ |
||
do j=1 to 100; z= j /*║ ║*/ |
do j=1 to 100; z= j /*║ ║*/ |
||
Line 8,559: | Line 8,559: | ||
if j//(3*5)==0 then z= 'FizzBuzz' /*║ ║*/ |
if j//(3*5)==0 then z= 'FizzBuzz' /*║ ║*/ |
||
say right(z, 8) /*╚═══════════════════════════════════╝*/ |
say right(z, 8) /*╚═══════════════════════════════════╝*/ |
||
end /*j*/ /*stick a fork in it, we're all done. */</ |
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' |
'''output''' |
||
<pre style="height:40ex"> |
<pre style="height:40ex"> |
||
Line 8,667: | Line 8,667: | ||
This version is a different form, but essentially identical to the '''IF-THEN''' (above), |
This version is a different form, but essentially identical to the '''IF-THEN''' (above), |
||
<br>but doesn't require the use of a temporary variable to hold/contain the output. |
<br>but doesn't require the use of a temporary variable to hold/contain the output. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/ |
||
/*╔═══════════════════════════════════╗*/ |
/*╔═══════════════════════════════════╗*/ |
||
do j=1 to 100 /*║ ║*/ |
do j=1 to 100 /*║ ║*/ |
||
Line 8,676: | Line 8,676: | ||
otherwise say right(j, 8) /*╚═══════════════════════════════════╝*/ |
otherwise say right(j, 8) /*╚═══════════════════════════════════╝*/ |
||
end /*select*/ |
end /*select*/ |
||
end /*j*/ /*stick a fork in it, we're all done. */</ |
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' is identical to the 1<sup>st</sup> REXX version. |
'''output''' is identical to the 1<sup>st</sup> REXX version. |
||
===two IF-THEN=== |
===two IF-THEN=== |
||
This version lends itself to expansion (such as using '''Jazz''' for multiples of '''7'''). |
This version lends itself to expansion (such as using '''Jazz''' for multiples of '''7'''). |
||
< |
<syntaxhighlight lang="rexx">/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/ |
||
do j=1 for 100; _= |
do j=1 for 100; _= |
||
Line 8,688: | Line 8,688: | ||
/* if j//7 ==0 then _=_'Jazz' */ /* ◄─── note that this is a comment. */ |
/* if j//7 ==0 then _=_'Jazz' */ /* ◄─── note that this is a comment. */ |
||
say right(word(_ j,1),8) |
say right(word(_ j,1),8) |
||
end /*j*/ /*stick a fork in it, we're all done. */</ |
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' is identical to the 1<sup>st</sup> REXX version. |
'''output''' is identical to the 1<sup>st</sup> REXX version. |
||
==="geek" version=== |
==="geek" version=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/ |
||
/* [↓] concise, but somewhat obtuse. */ |
/* [↓] concise, but somewhat obtuse. */ |
||
do j=1 for 100 |
do j=1 for 100 |
||
say right(word(word('Fizz', 1+(j//3\==0))word('Buzz', 1+(j//5\==0)) j, 1), 8) |
say right(word(word('Fizz', 1+(j//3\==0))word('Buzz', 1+(j//5\==0)) j, 1), 8) |
||
end /*j*/ |
end /*j*/ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' is identical to the 1<sup>st</sup> REXX version. <br><br> |
'''output''' is identical to the 1<sup>st</sup> REXX version. <br><br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
for n = 1 to 100 |
for n = 1 to 100 |
||
if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl |
if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl |
||
Line 8,708: | Line 8,708: | ||
else see "" + n + " = " + n + nl ok |
else see "" + n + " = " + n + nl ok |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Robotic}}== |
=={{header|Robotic}}== |
||
< |
<syntaxhighlight lang="robotic"> |
||
set "local1" to 1 |
set "local1" to 1 |
||
: "loop" |
: "loop" |
||
Line 8,738: | Line 8,738: | ||
: "done" |
: "done" |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
The '''wait for 10''' function is not really necessary, but it helps to slow down the output. |
The '''wait for 10''' function is not really necessary, but it helps to slow down the output. |
||
Line 8,772: | Line 8,772: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">1.upto(100) do |n| |
||
print "Fizz" if a = (n % 3).zero? |
print "Fizz" if a = (n % 3).zero? |
||
print "Buzz" if b = (n % 5).zero? |
print "Buzz" if b = (n % 5).zero? |
||
print n unless (a || b) |
print n unless (a || b) |
||
puts |
puts |
||
end</ |
end</syntaxhighlight> |
||
A bit more straightforward: |
A bit more straightforward: |
||
< |
<syntaxhighlight lang="ruby">(1..100).each do |n| |
||
puts if (n % 15).zero? |
puts if (n % 15).zero? |
||
"FizzBuzz" |
"FizzBuzz" |
||
Line 8,789: | Line 8,789: | ||
n |
n |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Enumerable#Lazy and classes: |
Enumerable#Lazy and classes: |
||
Line 8,795: | Line 8,795: | ||
i.e, grabbing the first 10 fizz numbers starting from 30, fizz = Fizz.new(30,10) #=> [30, 33, 36, 39, 42, 45, 48, 51, 54, 57] |
i.e, grabbing the first 10 fizz numbers starting from 30, fizz = Fizz.new(30,10) #=> [30, 33, 36, 39, 42, 45, 48, 51, 54, 57] |
||
< |
<syntaxhighlight lang="ruby"> |
||
class Enumerator::Lazy |
class Enumerator::Lazy |
||
def filter_map |
def filter_map |
||
Line 8,887: | Line 8,887: | ||
min(2,b) if b < f and b < fb |
min(2,b) if b < f and b < fb |
||
min(0,fb) if fb < b and fb < f |
min(0,fb) if fb < b and fb < f |
||
end</ |
end</syntaxhighlight> |
||
An example using string interpolation: |
An example using string interpolation: |
||
< |
<syntaxhighlight lang="ruby">(1..100).each do |n| |
||
v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}" |
v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}" |
||
puts v.empty? ? n : v |
puts v.empty? ? n : v |
||
end</ |
end</syntaxhighlight> |
||
Interpolation inspired one-liner: |
Interpolation inspired one-liner: |
||
< |
<syntaxhighlight lang="ruby">1.upto(100) { |n| puts "#{'Fizz' if n % 3 == 0}#{'Buzz' if n % 5 == 0}#{n if n % 3 != 0 && n % 5 != 0}" }</syntaxhighlight> |
||
An example using append: |
An example using append: |
||
< |
<syntaxhighlight lang="ruby">1.upto 100 do |n| |
||
r = '' |
r = '' |
||
r << 'Fizz' if n % 3 == 0 |
r << 'Fizz' if n % 3 == 0 |
||
Line 8,905: | Line 8,905: | ||
r << n.to_s if r.empty? |
r << n.to_s if r.empty? |
||
puts r |
puts r |
||
end</ |
end</syntaxhighlight> |
||
Yet another solution: |
Yet another solution: |
||
<lang>1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i }</ |
<syntaxhighlight lang="text">1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i }</syntaxhighlight> |
||
Yet another solution: |
Yet another solution: |
||
< |
<syntaxhighlight lang="ruby">1.upto(100){|i|puts'FizzBuzz '[n=i**4%-15,n+13]||i}</syntaxhighlight> |
||
Used Enumerable#cycle: |
Used Enumerable#cycle: |
||
< |
<syntaxhighlight lang="ruby">f = [nil, nil, :Fizz].cycle |
||
b = [nil, nil, nil, nil, :Buzz].cycle |
b = [nil, nil, nil, nil, :Buzz].cycle |
||
(1..100).each do |i| |
(1..100).each do |i| |
||
puts "#{f.next}#{b.next}"[/.+/] || i |
puts "#{f.next}#{b.next}"[/.+/] || i |
||
end</ |
end</syntaxhighlight> |
||
After beforehand preparing the Array which put the number from 1 to 100, it processes. |
After beforehand preparing the Array which put the number from 1 to 100, it processes. |
||
< |
<syntaxhighlight lang="ruby">seq = *0..100 |
||
{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}} |
{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}} |
||
puts seq.drop(1)</ |
puts seq.drop(1)</syntaxhighlight> |
||
Monkeypatch example: |
Monkeypatch example: |
||
< |
<syntaxhighlight lang="ruby">class Integer |
||
def fizzbuzz |
def fizzbuzz |
||
v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" |
v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" |
||
Line 8,933: | Line 8,933: | ||
end |
end |
||
puts *(1..100).map(&:fizzbuzz)</ |
puts *(1..100).map(&:fizzbuzz)</syntaxhighlight> |
||
Without mutable variables or inline printing. |
Without mutable variables or inline printing. |
||
< |
<syntaxhighlight lang="ruby">fizzbuzz = ->(i) do |
||
(i%15).zero? and next "FizzBuzz" |
(i%15).zero? and next "FizzBuzz" |
||
(i%3).zero? and next "Fizz" |
(i%3).zero? and next "Fizz" |
||
Line 8,943: | Line 8,943: | ||
end |
end |
||
puts (1..100).map(&fizzbuzz).join("\n")</ |
puts (1..100).map(&fizzbuzz).join("\n")</syntaxhighlight> |
||
[[Jump anywhere#Ruby]] has a worse example of FizzBuzz, using a continuation! |
[[Jump anywhere#Ruby]] has a worse example of FizzBuzz, using a continuation! |
||
Using Ruby 3's Pattern Matching: |
Using Ruby 3's Pattern Matching: |
||
< |
<syntaxhighlight lang="ruby"> |
||
1.upto(100) do |n| |
1.upto(100) do |n| |
||
puts case [(n % 3).zero?, (n % 5).zero?] |
puts case [(n % 3).zero?, (n % 5).zero?] |
||
Line 8,960: | Line 8,960: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby with RSpec}}== |
=={{header|Ruby with RSpec}}== |
||
Line 8,968: | Line 8,968: | ||
Your spec/fizzbuzz_spec.rb file should like this: |
Your spec/fizzbuzz_spec.rb file should like this: |
||
< |
<syntaxhighlight lang="ruby"> |
||
require 'fizzbuzz' |
require 'fizzbuzz' |
||
Line 9,009: | Line 9,009: | ||
end |
end |
||
end |
end |
||
</ |
</syntaxhighlight> |
||
There are many ways to get these tests to pass. Here is an example solution of what your lib/fizzbuzz.rb file could look like: |
There are many ways to get these tests to pass. Here is an example solution of what your lib/fizzbuzz.rb file could look like: |
||
< |
<syntaxhighlight lang="ruby"> |
||
def fizzbuzz(number) |
def fizzbuzz(number) |
||
return 'FizzBuzz' if is_divisible_by_fifteen?(number) |
return 'FizzBuzz' if is_divisible_by_fifteen?(number) |
||
Line 9,037: | Line 9,037: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
When writing Test Driven code, it's important to remember that you should use the Red, Green, Refactor cycle. Simply writing each of these code snippets independently would go against everything TDD is about. Here is a good video that takes you through the process of writing this [https://www.youtube.com/watch?v=CHTep2zQVAc&feature=youtu.be FizzBuzz implementation using Ruby & RSpec]. |
When writing Test Driven code, it's important to remember that you should use the Red, Green, Refactor cycle. Simply writing each of these code snippets independently would go against everything TDD is about. Here is a good video that takes you through the process of writing this [https://www.youtube.com/watch?v=CHTep2zQVAc&feature=youtu.be FizzBuzz implementation using Ruby & RSpec]. |
||
Line 9,047: | Line 9,047: | ||
Basic example with a for loop and match: |
Basic example with a for loop and match: |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
for i in 1..=100 { |
for i in 1..=100 { |
||
match (i % 3, i % 5) { |
match (i % 3, i % 5) { |
||
Line 9,056: | Line 9,056: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Using an iterator and immutable data: |
Using an iterator and immutable data: |
||
< |
<syntaxhighlight lang="rust">use std::borrow::Cow; |
||
fn main() { |
fn main() { |
||
Line 9,072: | Line 9,072: | ||
.for_each(|n| println!("{:?}", n)); |
.for_each(|n| println!("{:?}", n)); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
A folding iterator version, buffered with a single string allocation, by making use of expressions the <code>write!</code> macro. |
A folding iterator version, buffered with a single string allocation, by making use of expressions the <code>write!</code> macro. |
||
< |
<syntaxhighlight lang="rust">use std::fmt::Write; |
||
fn fizzbuzz() -> String { |
fn fizzbuzz() -> String { |
||
Line 9,093: | Line 9,093: | ||
fn main() { |
fn main() { |
||
println!("{}", fizzbuzz()); |
println!("{}", fizzbuzz()); |
||
}</ |
}</syntaxhighlight> |
||
Or the ultimate optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout. |
Or the ultimate optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout. |
||
< |
<syntaxhighlight lang="rust">#![no_std] |
||
#![feature(asm, lang_items, libc, no_std, start)] |
#![feature(asm, lang_items, libc, no_std, start)] |
||
Line 9,132: | Line 9,132: | ||
#[lang = "eh_personality"] extern fn eh_personality() {} |
#[lang = "eh_personality"] extern fn eh_personality() {} |
||
#[lang = "panic_fmt"] extern fn panic_fmt() {}</ |
#[lang = "panic_fmt"] extern fn panic_fmt() {}</syntaxhighlight> |
||
=={{header|Salmon}}== |
=={{header|Salmon}}== |
||
< |
<syntaxhighlight lang="salmon">iterate (x; [1...100]) |
||
((x % 15 == 0) ? "FizzBuzz" : |
((x % 15 == 0) ? "FizzBuzz" : |
||
((x % 3 == 0) ? "Fizz" : |
((x % 3 == 0) ? "Fizz" : |
||
((x % 5 == 0) ? "Buzz" : x)))!;</ |
((x % 5 == 0) ? "Buzz" : x)))!;</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="salmon">iterate (x; [1...100]) |
||
{ |
{ |
||
if (x % 15 == 0) |
if (x % 15 == 0) |
||
Line 9,150: | Line 9,150: | ||
else |
else |
||
x!; |
x!; |
||
};</ |
};</syntaxhighlight> |
||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
< |
<syntaxhighlight lang="sas">data _null_; |
||
do i=1 to 100; |
do i=1 to 100; |
||
if mod(i,15)=0 then put "FizzBuzz"; |
if mod(i,15)=0 then put "FizzBuzz"; |
||
Line 9,160: | Line 9,160: | ||
else put i; |
else put i; |
||
end; |
end; |
||
run;</ |
run;</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
main is |
main is |
||
loop i ::= 1.upto!(100); |
loop i ::= 1.upto!(100); |
||
Line 9,176: | Line 9,176: | ||
end; |
end; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 9,182: | Line 9,182: | ||
===Idiomatic scala code=== |
===Idiomatic scala code=== |
||
< |
<syntaxhighlight lang="scala">object FizzBuzz extends App { |
||
1 to 100 foreach { n => |
1 to 100 foreach { n => |
||
println((n % 3, n % 5) match { |
println((n % 3, n % 5) match { |
||
Line 9,191: | Line 9,191: | ||
}) |
}) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Geeky over-generalized solution ☺=== |
===Geeky over-generalized solution ☺=== |
||
< |
<syntaxhighlight lang="scala">def replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] = |
||
rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) => |
rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) => |
||
a fold(_ => b, s => b fold(_ => a, t => Right(s + t)))) |
a fold(_ => b, s => b fold(_ => a, t => Right(s + t)))) |
||
Line 9,200: | Line 9,200: | ||
def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity) |
def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity) |
||
1 to 100 map fizzbuzz foreach println</ |
1 to 100 map fizzbuzz foreach println</syntaxhighlight> |
||
===By a two-liners geek=== |
===By a two-liners geek=== |
||
< |
<syntaxhighlight lang="scala">def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMet |
||
for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))</ |
for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))</syntaxhighlight> |
||
===One-liner geek=== |
===One-liner geek=== |
||
< |
<syntaxhighlight lang="scala">for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))</syntaxhighlight> |
||
===Functional Scala=== |
===Functional Scala=== |
||
< |
<syntaxhighlight lang="scala">def fizzBuzzTerm(n: Int): String = |
||
if (n % 15 == 0) "FizzBuzz" |
if (n % 15 == 0) "FizzBuzz" |
||
else if (n % 3 == 0) "Fizz" |
else if (n % 3 == 0) "Fizz" |
||
Line 9,216: | Line 9,216: | ||
else n.toString |
else n.toString |
||
def fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)</ |
def fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)</syntaxhighlight> |
||
===Scala 3 (Dotty)=== |
===Scala 3 (Dotty)=== |
||
Written so as to introduce changes, with comments. |
Written so as to introduce changes, with comments. |
||
< |
<syntaxhighlight lang="scala">def fizzBuzzTerm(n: Int): String | Int = // union types |
||
(n % 3, n % 5) match // optional semantic indentation; no braces |
(n % 3, n % 5) match // optional semantic indentation; no braces |
||
case (0, 0) => "FizzBuzz" |
case (0, 0) => "FizzBuzz" |
||
Line 9,233: | Line 9,233: | ||
@main def run(): Unit = // @main for main method; can take custom args |
@main def run(): Unit = // @main for main method; can take custom args |
||
fizzBuzz.take(100).foreach(println)</ |
fizzBuzz.take(100).foreach(println)</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(do ((i 1 (+ i 1))) |
||
((> i 100)) |
((> i 100)) |
||
(display |
(display |
||
Line 9,243: | Line 9,243: | ||
((= 0 (modulo i 5)) "Buzz") |
((= 0 (modulo i 5)) "Buzz") |
||
(else i))) |
(else i))) |
||
(newline))</ |
(newline))</syntaxhighlight> |
||
Using a recursive procedure. |
Using a recursive procedure. |
||
< |
<syntaxhighlight lang="scheme">(define (fizzbuzz x y) |
||
(println |
(println |
||
(cond (( = (modulo x 15) 0 ) "FizzBuzz") |
(cond (( = (modulo x 15) 0 ) "FizzBuzz") |
||
Line 9,256: | Line 9,256: | ||
(if (< x y) (fizzbuzz (+ x 1) y))) |
(if (< x y) (fizzbuzz (+ x 1) y))) |
||
(fizzbuzz 1 100)</ |
(fizzbuzz 1 100)</syntaxhighlight> |
||
Approach with maps and filters, easier to change, less readable |
Approach with maps and filters, easier to change, less readable |
||
than the previous. |
than the previous. |
||
< |
<syntaxhighlight lang="scheme">(define (fizzbuzz x) |
||
(let ([words '((3 . "Fizz") |
(let ([words '((3 . "Fizz") |
||
(5 . "Buzz"))]) |
(5 . "Buzz"))]) |
||
Line 9,269: | Line 9,269: | ||
(fizzbuzz 15) |
(fizzbuzz 15) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sed}}== |
=={{header|Sed}}== |
||
< |
<syntaxhighlight lang="sed">#n |
||
# doesn't work if there's no input |
# doesn't work if there's no input |
||
# initialize counters (0 = empty) and value |
# initialize counters (0 = empty) and value |
||
Line 9,311: | Line 9,311: | ||
# loop until value = 100 |
# loop until value = 100 |
||
/100/q |
/100/q |
||
b loop</ |
b loop</syntaxhighlight> |
||
Using <tt>seq</tt>: |
Using <tt>seq</tt>: |
||
< |
<syntaxhighlight lang="sed"> |
||
seq 100 | sed '/.*[05]$/s//Buzz/;n;s//Buzz/;n;s//Buzz/;s/^[0-9]*/Fizz/' |
seq 100 | sed '/.*[05]$/s//Buzz/;n;s//Buzz/;n;s//Buzz/;s/^[0-9]*/Fizz/' |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== GNU sed === |
=== GNU sed === |
||
Line 9,323: | Line 9,323: | ||
Using <tt>seq</tt>: |
Using <tt>seq</tt>: |
||
< |
<syntaxhighlight lang="sed"> |
||
seq 100 | sed '0~3 s/.*/Fizz/; 0~5 s/[0-9]*$/Buzz/' |
seq 100 | sed '0~3 s/.*/Fizz/; 0~5 s/[0-9]*$/Buzz/' |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using <tt>yes</tt>: |
Using <tt>yes</tt>: |
||
< |
<syntaxhighlight lang="sed"> |
||
yes | sed -n '0~3s/y/Fizz/;0~5s/y*$/Buzz/;tx;=;b;:x;p;100q' |
yes | sed -n '0~3s/y/Fizz/;0~5s/y*$/Buzz/;tx;=;b;:x;p;100q' |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using the option ''-z (--zero-data)'' first introduced in GNU sed 4.2.2 (2012-12-22): |
Using the option ''-z (--zero-data)'' first introduced in GNU sed 4.2.2 (2012-12-22): |
||
< |
<syntaxhighlight lang="sed"> |
||
sed -nz '0~3s/^/Fizz/;0~5s/$/Buzz/;tx;=;b;:x;p;100q' /dev/zero | sed 'y/\c@/\n/' |
sed -nz '0~3s/^/Fizz/;0~5s/$/Buzz/;tx;=;b;:x;p;100q' /dev/zero | sed 'y/\c@/\n/' |
||
</syntaxhighlight> |
|||
</lang> |
|||
Second invocation of ''sed'' translates null characters to newlines. The same could be achieved with <tt>tr \\0 \\n</tt> |
Second invocation of ''sed'' translates null characters to newlines. The same could be achieved with <tt>tr \\0 \\n</tt> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 9,356: | Line 9,356: | ||
end if; |
end if; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
< |
<syntaxhighlight lang="sensetalk">repeat 100 |
||
put "" into output |
put "" into output |
||
if the counter is a multiple of 3 then |
if the counter is a multiple of 3 then |
||
Line 9,371: | Line 9,371: | ||
end if |
end if |
||
put output |
put output |
||
end repeat</ |
end repeat</syntaxhighlight> |
||
=={{header|SequenceL}}== |
=={{header|SequenceL}}== |
||
< |
<syntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>; |
||
import <Utilities/Sequence.sl>; |
import <Utilities/Sequence.sl>; |
||
Line 9,390: | Line 9,390: | ||
foreach i within 1 ... 100; |
foreach i within 1 ... 100; |
||
in |
in |
||
delimit(result, '\n');</ |
delimit(result, '\n');</syntaxhighlight> |
||
=={{header|Shale}}== |
=={{header|Shale}}== |
||
< |
<syntaxhighlight lang="shale">#!/usr/local/bin/shale |
||
string library |
string library |
||
Line 9,407: | Line 9,407: | ||
r "" equals string::() { i } { r } if i "%3d: %p\n" printf |
r "" equals string::() { i } { r } if i "%3d: %p\n" printf |
||
i++ |
i++ |
||
} while</ |
} while</syntaxhighlight> |
||
=={{header|Shen}}== |
=={{header|Shen}}== |
||
< |
<syntaxhighlight lang="shen">(define fizzbuzz |
||
101 -> (nl) |
101 -> (nl) |
||
N -> (let divisible-by? (/. A B (integer? (/ A B))) |
N -> (let divisible-by? (/. A B (integer? (/ A B))) |
||
Line 9,423: | Line 9,423: | ||
(fizzbuzz (+ N 1)))))) |
(fizzbuzz (+ N 1)))))) |
||
(fizzbuzz 1)</ |
(fizzbuzz 1)</syntaxhighlight> |
||
=== Alternative showing off other features like prolog integration and guards === |
=== Alternative showing off other features like prolog integration and guards === |
||
< |
<syntaxhighlight lang="shen">(defprolog fizz |
||
0 <-- (is _ (output "Fizz")); |
0 <-- (is _ (output "Fizz")); |
||
N <-- (when (> N 0)) (is N1 (- N 3)) (fizz N1); |
N <-- (when (> N 0)) (is N1 (- N 3)) (fizz N1); |
||
Line 9,455: | Line 9,455: | ||
(fizzbuzz 1 100) |
(fizzbuzz 1 100) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Structured: |
Structured: |
||
< |
<syntaxhighlight lang="ruby">{ |i| |
||
if (i %% 3) { |
if (i %% 3) { |
||
print "Fizz" |
print "Fizz" |
||
Line 9,467: | Line 9,467: | ||
elsif (i %% 5) { say "Buzz" } |
elsif (i %% 5) { say "Buzz" } |
||
else { say i } |
else { say i } |
||
} * 100</ |
} * 100</syntaxhighlight> |
||
Declarative: |
Declarative: |
||
< |
<syntaxhighlight lang="ruby">func fizzbuzz({ _ %% 15 }) { "FizzBuzz" } |
||
func fizzbuzz({ _ %% 5 }) { "Buzz" } |
func fizzbuzz({ _ %% 5 }) { "Buzz" } |
||
func fizzbuzz({ _ %% 3 }) { "Fizz" } |
func fizzbuzz({ _ %% 3 }) { "Fizz" } |
||
func fizzbuzz( n ) { n } |
func fizzbuzz( n ) { n } |
||
for n in (1..100) { say fizzbuzz(n) }</ |
for n in (1..100) { say fizzbuzz(n) }</syntaxhighlight> |
||
One-liner: |
One-liner: |
||
< |
<syntaxhighlight lang="ruby">{|i|say "#{<Fizz>[i%3]}#{<Buzz>[i%5]}"||i}*100</syntaxhighlight> |
||
=={{header|Simula}}== |
=={{header|Simula}}== |
||
< |
<syntaxhighlight lang="simula">begin |
||
integer i; |
integer i; |
||
for i := 1 step 1 until 100 do |
for i := 1 step 1 until 100 do |
||
Line 9,495: | Line 9,495: | ||
outimage |
outimage |
||
end; |
end; |
||
end</ |
end</syntaxhighlight> |
||
=={{header|SkookumScript}}== |
=={{header|SkookumScript}}== |
||
Answer by printing out one of the 4 alternatives: |
Answer by printing out one of the 4 alternatives: |
||
< |
<syntaxhighlight lang="javascript"> |
||
1.to 100 |
1.to 100 |
||
[ |
[ |
||
Line 9,508: | Line 9,508: | ||
else [idx]) |
else [idx]) |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Answer by building up a string: |
Answer by building up a string: |
||
< |
<syntaxhighlight lang="javascript"> |
||
1.to 100 |
1.to 100 |
||
[ |
[ |
||
Line 9,519: | Line 9,519: | ||
println(if str.empty? [idx] else [str]) |
println(if str.empty? [idx] else [str]) |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or doing initial bind in one step: |
Or doing initial bind in one step: |
||
< |
<syntaxhighlight lang="javascript"> |
||
1.to 100 |
1.to 100 |
||
[ |
[ |
||
Line 9,529: | Line 9,529: | ||
println(if str.empty? [idx] else [str]) |
println(if str.empty? [idx] else [str]) |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">n@(Integer traits) fizzbuzz |
||
[ |
[ |
||
output ::= ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: ['']) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: ['']). |
output ::= ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: ['']) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: ['']). |
||
output isEmpty ifTrue: [n printString] ifFalse: [output] |
output isEmpty ifTrue: [n printString] ifFalse: [output] |
||
]. |
]. |
||
1 to: 100 do: [| :i | inform: i fizzbuzz]</ |
1 to: 100 do: [| :i | inform: i fizzbuzz]</syntaxhighlight> |
||
=={{header|Small}}== |
=={{header|Small}}== |
||
Line 9,544: | Line 9,544: | ||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Since only GNU Smalltalk supports file-based programming, we'll be using its syntax. |
Since only GNU Smalltalk supports file-based programming, we'll be using its syntax. |
||
< |
<syntaxhighlight lang="smalltalk">Integer extend [ |
||
fizzbuzz [ |
fizzbuzz [ |
||
| fb | |
| fb | |
||
Line 9,552: | Line 9,552: | ||
] |
] |
||
] |
] |
||
1 to: 100 do: [ :i | i fizzbuzz displayNl ]</ |
1 to: 100 do: [ :i | i fizzbuzz displayNl ]</syntaxhighlight> |
||
A Squeak/Pharo example using the Transcript window: |
A Squeak/Pharo example using the Transcript window: |
||
< |
<syntaxhighlight lang="smalltalk">(1 to: 100) do: |
||
[:n | |
[:n | |
||
((n \\ 3)*(n \\ 5)) isZero |
((n \\ 3)*(n \\ 5)) isZero |
||
Line 9,562: | Line 9,562: | ||
(n \\ 5) isZero |
(n \\ 5) isZero |
||
ifTrue: [Transcript show: 'Buzz']. |
ifTrue: [Transcript show: 'Buzz']. |
||
Transcript cr.]</ |
Transcript cr.]</syntaxhighlight> |
||
The Squeak/Pharo examples below present possibilities using the powerful classes available. In this example, the dictionary can have as keys pairs of booleans and in the interaction the several boolean patterns select the string to be printed or if the pattern is not found the number itself is printed. |
The Squeak/Pharo examples below present possibilities using the powerful classes available. In this example, the dictionary can have as keys pairs of booleans and in the interaction the several boolean patterns select the string to be printed or if the pattern is not found the number itself is printed. |
||
< |
<syntaxhighlight lang="smalltalk">fizzbuzz := Dictionary with: #(true true)->'FizzBuzz' |
||
with: #(true false)->'Fizz' |
with: #(true false)->'Fizz' |
||
with: #(false true)->'Buzz'. |
with: #(false true)->'Buzz'. |
||
Line 9,571: | Line 9,571: | ||
[ :i | Transcript show: |
[ :i | Transcript show: |
||
(fizzbuzz at: {i isDivisibleBy: 3. i isDivisibleBy: 5} |
(fizzbuzz at: {i isDivisibleBy: 3. i isDivisibleBy: 5} |
||
ifAbsent: [ i ]); cr]</ |
ifAbsent: [ i ]); cr]</syntaxhighlight> |
||
Smalltalk does not have a case-select construct, but a similar effect can be attained using a collection and the #includes: method: |
Smalltalk does not have a case-select construct, but a similar effect can be attained using a collection and the #includes: method: |
||
< |
<syntaxhighlight lang="smalltalk">1 to: 100 do: [:n | |r| |
||
r := n rem: 15. |
r := n rem: 15. |
||
Transcript show: (r isZero |
Transcript show: (r isZero |
||
Line 9,582: | Line 9,582: | ||
ifTrue:['buzz'] |
ifTrue:['buzz'] |
||
ifFalse:[n]]]); |
ifFalse:[n]]]); |
||
cr].</ |
cr].</syntaxhighlight> |
||
If the construction of the whole collection is done beforehand, Smalltalk provides a straightforward way of doing because collections can be heterogeneous (may contain any object): |
If the construction of the whole collection is done beforehand, Smalltalk provides a straightforward way of doing because collections can be heterogeneous (may contain any object): |
||
< |
<syntaxhighlight lang="smalltalk">fbz := (1 to: 100) asOrderedCollection. |
||
3 to: 100 by: 3 do: [:i | fbz at: i put: 'Fizz']. |
3 to: 100 by: 3 do: [:i | fbz at: i put: 'Fizz']. |
||
5 to: 100 by: 5 do: [:i | fbz at: i put: 'Buzz']. |
5 to: 100 by: 5 do: [:i | fbz at: i put: 'Buzz']. |
||
15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz']. |
15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz']. |
||
fbz do: [:i | Transcript show: i; cr].</ |
fbz do: [:i | Transcript show: i; cr].</syntaxhighlight> |
||
The approach building a dynamic string can be done as well: |
The approach building a dynamic string can be done as well: |
||
< |
<syntaxhighlight lang="smalltalk">1 to: 100 do: [:i | |fb s| |
||
fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}. |
fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}. |
||
fb at: 3 put: (fb first | fb second) not. |
fb at: 3 put: (fb first | fb second) not. |
||
s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}. |
s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}. |
||
Transcript show: (s expandMacrosWithArguments: fb); cr].</ |
Transcript show: (s expandMacrosWithArguments: fb); cr].</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Merely posting a solution by Daniel Lyons |
Merely posting a solution by Daniel Lyons |
||
< |
<syntaxhighlight lang="snobol4"> I = 1 |
||
LOOP FIZZBUZZ = "" |
LOOP FIZZBUZZ = "" |
||
EQ(REMDR(I, 3), 0) :F(TRY_5) |
EQ(REMDR(I, 3), 0) :F(TRY_5) |
||
Line 9,609: | Line 9,609: | ||
I = I + 1 |
I = I + 1 |
||
LE(I, 100) :S(LOOP) |
LE(I, 100) :S(LOOP) |
||
END</ |
END</syntaxhighlight> |
||
=={{header|SNUSP}}== |
=={{header|SNUSP}}== |
||
Line 9,617: | Line 9,617: | ||
{{libheader|SQL}} |
{{libheader|SQL}} |
||
===Oracle SQL=== |
===Oracle SQL=== |
||
< |
<syntaxhighlight lang="sql">SELECT CASE |
||
WHEN MOD(level,15)=0 THEN 'FizzBuzz' |
WHEN MOD(level,15)=0 THEN 'FizzBuzz' |
||
WHEN MOD(level,3)=0 THEN 'Fizz' |
WHEN MOD(level,3)=0 THEN 'Fizz' |
||
Line 9,624: | Line 9,624: | ||
END FizzBuzz |
END FizzBuzz |
||
FROM dual |
FROM dual |
||
CONNECT BY LEVEL <= 100;</ |
CONNECT BY LEVEL <= 100;</syntaxhighlight> |
||
Or using Oracle's DECODE and NVL: |
Or using Oracle's DECODE and NVL: |
||
< |
<syntaxhighlight lang="sql">SELECT nvl(decode(MOD(level,3),0,'Fizz')||decode(MOD(level,5),0,'Buzz'),level) |
||
FROM dual |
FROM dual |
||
CONNECT BY level<=100;</ |
CONNECT BY level<=100;</syntaxhighlight> |
||
===PostgreSQL specific=== |
===PostgreSQL specific=== |
||
< |
<syntaxhighlight lang="sql">SELECT i, fizzbuzz |
||
FROM |
FROM |
||
(SELECT i, |
(SELECT i, |
||
Line 9,641: | Line 9,641: | ||
END AS fizzbuzz |
END AS fizzbuzz |
||
FROM generate_series(1,100) AS i) AS fb |
FROM generate_series(1,100) AS i) AS fb |
||
WHERE fizzbuzz IS NOT NULL;</ |
WHERE fizzbuzz IS NOT NULL;</syntaxhighlight> |
||
Using Generate_Series and tables only: |
Using Generate_Series and tables only: |
||
< |
<syntaxhighlight lang="sql">SELECT COALESCE(FIZZ || BUZZ, FIZZ, BUZZ, OUTPUT) AS FIZZBUZZ FROM |
||
(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT |
(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT |
||
FROM GENERATE_SERIES(1,100)) F LEFT JOIN |
FROM GENERATE_SERIES(1,100)) F LEFT JOIN |
||
Line 9,650: | Line 9,650: | ||
FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN |
FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN |
||
(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON |
(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON |
||
BUZZ.BUZZ_SERIES = F.FULL_SERIES;</ |
BUZZ.BUZZ_SERIES = F.FULL_SERIES;</syntaxhighlight> |
||
===Recursive Common Table Expressions (MSSQL 2005+)=== |
===Recursive Common Table Expressions (MSSQL 2005+)=== |
||
< |
<syntaxhighlight lang="sql">WITH nums (n, fizzbuzz ) AS ( |
||
SELECT 1, CONVERT(nvarchar, 1) UNION ALL |
SELECT 1, CONVERT(nvarchar, 1) UNION ALL |
||
SELECT |
SELECT |
||
Line 9,667: | Line 9,667: | ||
SELECT n, fizzbuzz FROM nums |
SELECT n, fizzbuzz FROM nums |
||
ORDER BY n ASC |
ORDER BY n ASC |
||
OPTION ( MAXRECURSION 100 )</ |
OPTION ( MAXRECURSION 100 )</syntaxhighlight> |
||
===Generic SQL using a join=== |
===Generic SQL using a join=== |
||
This should work in most RDBMSs, but you may need to change <tt>MOD(i,divisor)</tt> to <tt>i % divisor</tt>. |
This should work in most RDBMSs, but you may need to change <tt>MOD(i,divisor)</tt> to <tt>i % divisor</tt>. |
||
< |
<syntaxhighlight lang="sql">-- Load some numbers |
||
CREATE TABLE numbers(i INTEGER); |
CREATE TABLE numbers(i INTEGER); |
||
INSERT INTO numbers VALUES(1); |
INSERT INTO numbers VALUES(1); |
||
Line 9,693: | Line 9,693: | ||
-- Tidy up |
-- Tidy up |
||
DROP TABLE fizzbuzz; |
DROP TABLE fizzbuzz; |
||
DROP TABLE numbers;</ |
DROP TABLE numbers;</syntaxhighlight> |
||
=={{header|Squirrel}}== |
=={{header|Squirrel}}== |
||
< |
<syntaxhighlight lang="javascript">function Fizzbuzz(n) { |
||
for (local i = 1; i <= n; i += 1) { |
for (local i = 1; i <= n; i += 1) { |
||
if (i % 15 == 0) |
if (i % 15 == 0) |
||
Line 9,709: | Line 9,709: | ||
} |
} |
||
} |
} |
||
Fizzbuzz(100);</ |
Fizzbuzz(100);</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">program define fizzbuzz |
||
args n |
args n |
||
forvalues i = 1/`n' { |
forvalues i = 1/`n' { |
||
Line 9,728: | Line 9,728: | ||
} |
} |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Swahili}}== |
=={{header|Swahili}}== |
||
< |
<syntaxhighlight lang="swahili"> |
||
shughuli fizzBuzz() { |
shughuli fizzBuzz() { |
||
kwa i = 1 mpaka 100 { |
kwa i = 1 mpaka 100 { |
||
Line 9,745: | Line 9,745: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
=== using a switch statement === |
=== using a switch statement === |
||
< |
<syntaxhighlight lang="swift">for i in 1...100 { |
||
switch (i % 3, i % 5) { |
switch (i % 3, i % 5) { |
||
case (0, 0): |
case (0, 0): |
||
Line 9,760: | Line 9,760: | ||
print(i) |
print(i) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=== using two if statements and an Optional === |
=== using two if statements and an Optional === |
||
< |
<syntaxhighlight lang="swift">for i in 1...100{ |
||
var s:String? |
var s:String? |
||
if i%3==0{s="Fizz"} |
if i%3==0{s="Fizz"} |
||
if i%5==0{s=(s ?? "")+"Buzz"} |
if i%5==0{s=(s ?? "")+"Buzz"} |
||
print(s ?? i) |
print(s ?? i) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Symsyn}}== |
=={{header|Symsyn}}== |
||
< |
<syntaxhighlight lang="symsyn"> |
||
| FizzBuzz |
| FizzBuzz |
||
Line 9,793: | Line 9,793: | ||
goif |
goif |
||
endif |
endif |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
templates fizz |
templates fizz |
||
$ mod 3 -> # |
$ mod 3 -> # |
||
Line 9,809: | Line 9,809: | ||
[ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](when <=''> do $i ! otherwise $ !\)... -> '$; |
[ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](when <=''> do $i ! otherwise $ !\)... -> '$; |
||
' -> !OUT::write |
' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">proc fizzbuzz {n {m1 3} {m2 5}} { |
||
for {set i 1} {$i <= $n} {incr i} { |
for {set i 1} {$i <= $n} {incr i} { |
||
set ans "" |
set ans "" |
||
Line 9,820: | Line 9,820: | ||
} |
} |
||
} |
} |
||
fizzbuzz 100</ |
fizzbuzz 100</syntaxhighlight> |
||
The following example shows Tcl's substitution mechanism that allows to concatenate the results of two successive commands into a string: |
The following example shows Tcl's substitution mechanism that allows to concatenate the results of two successive commands into a string: |
||
< |
<syntaxhighlight lang="tcl">while {[incr i] < 101} { |
||
set fb [if {$i % 3 == 0} {list Fizz}][if {$i % 5 == 0} {list Buzz}] |
set fb [if {$i % 3 == 0} {list Fizz}][if {$i % 5 == 0} {list Buzz}] |
||
if {$fb ne ""} {puts $fb} {puts $i} |
if {$fb ne ""} {puts $fb} {puts $i} |
||
}</ |
}</syntaxhighlight> |
||
This version uses list rotation, so avoiding an explicit mod operation: |
This version uses list rotation, so avoiding an explicit mod operation: |
||
< |
<syntaxhighlight lang="tcl">set f [lrepeat 5 "Fizz" {$i} {$i}] |
||
foreach i {5 10} {lset f $i "Buzz"};lset f 0 "FizzBuzz" |
foreach i {5 10} {lset f $i "Buzz"};lset f 0 "FizzBuzz" |
||
for {set i 1} {$i <= 100} {incr i} { |
for {set i 1} {$i <= 100} {incr i} { |
||
puts [subst [lindex [set f [list {*}[lassign $f ff] $ff]] 0]] |
puts [subst [lindex [set f [list {*}[lassign $f ff] $ff]] 0]] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
Line 9,840: | Line 9,840: | ||
=={{header|TransFORTH}}== |
=={{header|TransFORTH}}== |
||
< |
<syntaxhighlight lang="forth">: FIZZBUZZ |
||
101 1 DO |
101 1 DO |
||
I 15 MOD 0 = IF |
I 15 MOD 0 = IF |
||
Line 9,849: | Line 9,849: | ||
PRINT " BUZZ " |
PRINT " BUZZ " |
||
ELSE I . THEN THEN THEN |
ELSE I . THEN THEN THEN |
||
CR LOOP ;</ |
CR LOOP ;</syntaxhighlight> |
||
=={{header|True BASIC}}== |
=={{header|True BASIC}}== |
||
Line 9,855: | Line 9,855: | ||
=={{header|Turing}}== |
=={{header|Turing}}== |
||
< |
<syntaxhighlight lang="turing">for i : 1 .. 100 |
||
if i mod 15 = 0 then |
if i mod 15 = 0 then |
||
put "Fizzbuzz" |
put "Fizzbuzz" |
||
Line 9,865: | Line 9,865: | ||
put i |
put i |
||
end if |
end if |
||
end for</ |
end for</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript">$$ MODE TUSCRIPT |
||
LOOP n=1,100 |
LOOP n=1,100 |
||
mod=MOD (n,15) |
mod=MOD (n,15) |
||
Line 9,881: | Line 9,881: | ||
PRINT n |
PRINT n |
||
ENDSELECT |
ENDSELECT |
||
ENDLOOP</ |
ENDLOOP</syntaxhighlight> |
||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
< |
<syntaxhighlight lang="shell">$ txr -p "(mapcar (op if @1 @1 @2) (repeat '(nil nil fizz nil buzz fizz nil nil fizz buzz nil fizz nil nil fizzbuzz)) (range 1 100))"</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
This solution should work with any Bourne-compatible shell: <!-- http://ideone.com/usJXGo --> |
This solution should work with any Bourne-compatible shell: <!-- http://ideone.com/usJXGo --> |
||
< |
<syntaxhighlight lang="bash">i=1 |
||
while expr $i '<=' 100 >/dev/null; do |
while expr $i '<=' 100 >/dev/null; do |
||
w=false |
w=false |
||
Line 9,895: | Line 9,895: | ||
if $w; then echo; else echo $i; fi |
if $w; then echo; else echo $i; fi |
||
i=`expr $i + 1` |
i=`expr $i + 1` |
||
done</ |
done</syntaxhighlight> |
||
===Versions for specific shells=== |
===Versions for specific shells=== |
||
Line 9,903: | Line 9,903: | ||
and it should work with every POSIX shell. |
and it should work with every POSIX shell. |
||
<!-- http://ideone.com/5yZmOz --> |
<!-- http://ideone.com/5yZmOz --> |
||
< |
<syntaxhighlight lang="bash">n=1 |
||
while [ 100 -ge n ]; do |
while [ 100 -ge n ]; do |
||
if [ $((n % 15)) -eq 0 ]; then |
if [ $((n % 15)) -eq 0 ]; then |
||
Line 9,915: | Line 9,915: | ||
fi |
fi |
||
n=$((n + 1)) |
n=$((n + 1)) |
||
done</ |
done</syntaxhighlight> |
||
The next solution requires the <code>(( ))</code> command from the [[Korn Shell]]. |
The next solution requires the <code>(( ))</code> command from the [[Korn Shell]]. |
||
{{works with|pdksh|5.2.14}} |
{{works with|pdksh|5.2.14}} |
||
< |
<syntaxhighlight lang="bash">NUM=1 |
||
until ((NUM == 101)) ; do |
until ((NUM == 101)) ; do |
||
if ((NUM % 15 == 0)) ; then |
if ((NUM % 15 == 0)) ; then |
||
Line 9,931: | Line 9,931: | ||
fi |
fi |
||
((NUM = NUM + 1)) |
((NUM = NUM + 1)) |
||
done</ |
done</syntaxhighlight> |
||
A version using concatenation: |
A version using concatenation: |
||
{{works with|bash|3}} |
{{works with|bash|3}} |
||
< |
<syntaxhighlight lang="bash">for ((n=1; n<=100; n++)) |
||
do |
do |
||
fb='' |
fb='' |
||
Line 9,941: | Line 9,941: | ||
[ $(( n % 5 )) -eq 0 ] && fb="${fb}Buzz" |
[ $(( n % 5 )) -eq 0 ] && fb="${fb}Buzz" |
||
[ -n "${fb}" ] && echo "${fb}" || echo "$n" |
[ -n "${fb}" ] && echo "${fb}" || echo "$n" |
||
done</ |
done</syntaxhighlight> |
||
A version using some of the insane overkill of Bash 4: |
A version using some of the insane overkill of Bash 4: |
||
{{works with|bash|4}} |
{{works with|bash|4}} |
||
< |
<syntaxhighlight lang="bash">command_not_found_handle () { |
||
local Fizz=3 Buzz=5 |
local Fizz=3 Buzz=5 |
||
[ $(( $2 % $1 )) -eq 0 ] && echo -n $1 && [ ${!1} -eq 3 ] |
[ $(( $2 % $1 )) -eq 0 ] && echo -n $1 && [ ${!1} -eq 3 ] |
||
Line 9,954: | Line 9,954: | ||
Fizz $i && ! Buzz $i || echo -n $i |
Fizz $i && ! Buzz $i || echo -n $i |
||
echo |
echo |
||
done</ |
done</syntaxhighlight> |
||
Bash one-liner: <!-- http://ideone.com/xMEGFK --> |
Bash one-liner: <!-- http://ideone.com/xMEGFK --> |
||
< |
<syntaxhighlight lang="bash">for i in {1..100};do ((($i%15==0))&& echo FizzBuzz)||((($i%5==0))&& echo Buzz;)||((($i%3==0))&& echo Fizz;)||echo $i;done</syntaxhighlight> |
||
==={{header|C Shell}}=== |
==={{header|C Shell}}=== |
||
< |
<syntaxhighlight lang="csh">@ n = 1 |
||
while ( $n <= 100 ) |
while ( $n <= 100 ) |
||
if ($n % 15 == 0) then |
if ($n % 15 == 0) then |
||
Line 9,972: | Line 9,972: | ||
endif |
endif |
||
@ n += 1 |
@ n += 1 |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
< |
<syntaxhighlight lang="ursa"># |
||
# fizzbuzz |
# fizzbuzz |
||
# |
# |
||
Line 9,990: | Line 9,990: | ||
end if |
end if |
||
out endl console |
out endl console |
||
end for</ |
end for</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
Line 10,000: | Line 10,000: | ||
#show+ |
#show+ |
||
main = fizzbuzz*t iota 101</ |
main = fizzbuzz*t iota 101</syntaxhighlight> |
||
=={{header|V}}== |
=={{header|V}}== |
||
< |
<syntaxhighlight lang="v">[fizzbuzz |
||
1 [>=] [ |
1 [>=] [ |
||
[[15 % zero?] ['fizzbuzz' puts] |
[[15 % zero?] ['fizzbuzz' puts] |
||
Line 10,011: | Line 10,011: | ||
] when succ |
] when succ |
||
] while]. |
] while]. |
||
|100 fizzbuzz</ |
|100 fizzbuzz</syntaxhighlight> |
||
===Second try=== |
===Second try=== |
||
Line 10,017: | Line 10,017: | ||
define a command that will generate a sequence |
define a command that will generate a sequence |
||
< |
<syntaxhighlight lang="v">[seq [] swap dup [zero? not] [rolldown [dup] dip cons rollup pred] while pop pop].</syntaxhighlight> |
||
create a quote that will return a quote that returns a quote if its argument is an integer (A HOF) |
create a quote that will return a quote that returns a quote if its argument is an integer (A HOF) |
||
< |
<syntaxhighlight lang="v">[check [N X F : [[integer?] [[X % zero?] [N F cons] if] if]] view].</syntaxhighlight> |
||
Create a quote that will make sure that the above quote is applied correctly if given (Number Function) |
Create a quote that will make sure that the above quote is applied correctly if given (Number Function) |
||
as arguments. |
as arguments. |
||
< |
<syntaxhighlight lang="v">[func [[N F] : [dup N F check i] ] view map].</syntaxhighlight> |
||
And apply it |
And apply it |
||
< |
<syntaxhighlight lang="v">100 seq [ |
||
[15 [pop 'fizzbuzz' puts]] |
[15 [pop 'fizzbuzz' puts]] |
||
[5 [pop 'buzz' puts]] |
[5 [pop 'buzz' puts]] |
||
[3 [pop 'fizz' puts]] |
[3 [pop 'fizz' puts]] |
||
[1 [puts]]] [func dup] step |
[1 [puts]]] [func dup] step |
||
[i true] map pop</ |
[i true] map pop</syntaxhighlight> |
||
the first one is much better :) |
the first one is much better :) |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">int main() { |
||
for (int i = 1; i <= 100; i++) { |
for (int i = 1; i <= 100; i++) { |
||
if (i % 3 == 0) stdout.printf("Fizz\n"); |
if (i % 3 == 0) stdout.printf("Fizz\n"); |
||
Line 10,042: | Line 10,042: | ||
} |
} |
||
return 0;; |
return 0;; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|VAX Assembly}}== |
=={{header|VAX Assembly}}== |
||
< |
<syntaxhighlight lang="vax assembly"> 00000008 0000 1 len =8 |
||
00000008 0000 2 msg: .blkb len ;output buffer |
00000008 0000 2 msg: .blkb len ;output buffer |
||
0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field |
0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field |
||
Line 10,087: | Line 10,087: | ||
9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml |
9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml |
||
04 0084 42 ret |
04 0084 42 ret |
||
0085 43 .end start</ |
0085 43 .end start</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Option Explicit |
Option Explicit |
||
Line 10,109: | Line 10,109: | ||
Next |
Next |
||
Debug.Print Join(Tb, vbCrLf) |
Debug.Print Join(Tb, vbCrLf) |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
As an alternative, testing each number only once: |
As an alternative, testing each number only once: |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Sub FizzBuzz() |
Sub FizzBuzz() |
||
Dim i As Integer |
Dim i As Integer |
||
Line 10,122: | Line 10,122: | ||
Debug.Print Join(T, ", ") & ", Buzz" |
Debug.Print Join(T, ", ") & ", Buzz" |
||
End Sub |
End Sub |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
{{works with|Windows Script Host|*}} |
{{works with|Windows Script Host|*}} |
||
< |
<syntaxhighlight lang="vbscript">For i = 1 To 100 |
||
If i Mod 15 = 0 Then |
If i Mod 15 = 0 Then |
||
WScript.Echo "FizzBuzz" |
WScript.Echo "FizzBuzz" |
||
Line 10,136: | Line 10,136: | ||
WScript.Echo i |
WScript.Echo i |
||
End If |
End If |
||
Next</ |
Next</syntaxhighlight> |
||
=====An Alternative===== |
=====An Alternative===== |
||
{{works with|Windows Script Host|*}} |
{{works with|Windows Script Host|*}} |
||
< |
<syntaxhighlight lang="vbscript">With WScript.StdOut |
||
For i = 1 To 100 |
For i = 1 To 100 |
||
If i Mod 3 = 0 Then .Write "Fizz" |
If i Mod 3 = 0 Then .Write "Fizz" |
||
Line 10,146: | Line 10,146: | ||
If .Column = 1 Then .WriteLine i Else .WriteLine "" |
If .Column = 1 Then .WriteLine i Else .WriteLine "" |
||
Next |
Next |
||
End With</ |
End With</syntaxhighlight> |
||
=={{header|Verbexx}}== |
=={{header|Verbexx}}== |
||
< |
<syntaxhighlight lang="verbexx">@LOOP init:{@VAR t3 t5; @VAR i = 1} while:(i <= 100) next:{i++} |
||
{ |
{ |
||
t3 = (i % 3 == 0); |
t3 = (i % 3 == 0); |
||
Line 10,159: | Line 10,159: | ||
else: { i } |
else: { i } |
||
); |
); |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Verilog}}== |
=={{header|Verilog}}== |
||
<syntaxhighlight lang="verilog"> |
|||
<lang Verilog> |
|||
module main; |
module main; |
||
integer number; |
integer number; |
||
Line 10,182: | Line 10,182: | ||
end |
end |
||
endmodule |
endmodule |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VHDL}}== |
=={{header|VHDL}}== |
||
< |
<syntaxhighlight lang="vhdl">entity fizzbuzz is |
||
end entity fizzbuzz; |
end entity fizzbuzz; |
||
Line 10,214: | Line 10,214: | ||
end process p_fizz; |
end process p_fizz; |
||
end architecture beh;</ |
end architecture beh;</syntaxhighlight> |
||
=={{header|Vim Script}}== |
=={{header|Vim Script}}== |
||
< |
<syntaxhighlight lang="vim">for i in range(1, 100) |
||
if i % 15 == 0 |
if i % 15 == 0 |
||
echo "FizzBuzz" |
echo "FizzBuzz" |
||
Line 10,227: | Line 10,227: | ||
echo i |
echo i |
||
endif |
endif |
||
endfor</ |
endfor</syntaxhighlight> |
||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
Line 10,233: | Line 10,233: | ||
=={{header|Visual Prolog}}== |
=={{header|Visual Prolog}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
implement main |
implement main |
||
open core, console |
open core, console |
||
Line 10,256: | Line 10,256: | ||
goal |
goal |
||
console::runUtf8(main::run). |
console::runUtf8(main::run). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
Updated for Vlang version 0.2.2 |
Updated for Vlang version 0.2.2 |
||
< |
<syntaxhighlight lang="go">const ( |
||
fizz = Tuple{true, false} |
fizz = Tuple{true, false} |
||
buzz = Tuple{false, true} |
buzz = Tuple{false, true} |
||
Line 10,289: | Line 10,289: | ||
fizzbuzz(15) |
fizzbuzz(15) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>1 |
<pre>1 |
||
Line 10,310: | Line 10,310: | ||
Basic example with a for loop and match: |
Basic example with a for loop and match: |
||
<syntaxhighlight lang="go"> |
|||
<lang go> |
|||
fn main() { |
fn main() { |
||
mut i := 1 |
mut i := 1 |
||
Line 10,323: | Line 10,323: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Another basic example using the ubiquitous if/else (if) statement: |
Another basic example using the ubiquitous if/else (if) statement: |
||
<syntaxhighlight lang="go"> |
|||
<lang go> |
|||
fn main() { |
fn main() { |
||
for i in 1..100 { |
for i in 1..100 { |
||
Line 10,341: | Line 10,341: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre style="height:40ex"> |
<pre style="height:40ex"> |
||
Line 10,447: | Line 10,447: | ||
=={{header|VTL-2}}== |
=={{header|VTL-2}}== |
||
< |
<syntaxhighlight lang="vtl2">10 N=1 |
||
20 #=30 |
20 #=30 |
||
30 #=N/3*0+%=0*110 |
30 #=N/3*0+%=0*110 |
||
Line 10,461: | Line 10,461: | ||
130 ?="Buzz"; |
130 ?="Buzz"; |
||
140 #=! |
140 #=! |
||
180 #=70</ |
180 #=70</syntaxhighlight> |
||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">for i 1 (i <= 100) ++i |
||
prn (if (divides i 15) |
prn (if (divides i 15) |
||
"FizzBuzz" |
"FizzBuzz" |
||
Line 10,472: | Line 10,472: | ||
"Buzz" |
"Buzz" |
||
:else |
:else |
||
i)</ |
i)</syntaxhighlight> |
||
=={{header|WDTE}}== |
=={{header|WDTE}}== |
||
< |
<syntaxhighlight lang="wdte">let io => import 'io'; |
||
let s => import 'stream'; |
let s => import 'stream'; |
||
Line 10,487: | Line 10,487: | ||
} -- io.writeln io.stdout; |
} -- io.writeln io.stdout; |
||
s.range 1 101 -> s.map fizzbuzz -> s.drain;</ |
s.range 1 101 -> s.map fizzbuzz -> s.drain;</syntaxhighlight> |
||
=={{header|Whitespace}}== |
=={{header|Whitespace}}== |
||
Line 10,493: | Line 10,493: | ||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@each &x!console.log x !*&x?{%%x 15 "FizzBuzz" %%x 5 "Buzz" %%x 3 "Fizz" x} @to 100</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">for (i in 1..100) { |
||
if (i % 15 == 0) { |
if (i % 15 == 0) { |
||
System.print("FizzBuzz") |
System.print("FizzBuzz") |
||
Line 10,506: | Line 10,506: | ||
System.print(i) |
System.print(i) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 10,613: | Line 10,613: | ||
=={{header|X86 Assembly}}== |
=={{header|X86 Assembly}}== |
||
< |
<syntaxhighlight lang="x86asm"> |
||
; x86_64 linux nasm |
; x86_64 linux nasm |
||
Line 10,718: | Line 10,718: | ||
syscall |
syscall |
||
ret |
ret |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
< |
<syntaxhighlight lang="lisp">(defun fizzbuzz () |
||
(defun fizzb (x y) |
(defun fizzb (x y) |
||
(display (cond |
(display (cond |
||
Line 10,733: | Line 10,733: | ||
(fizzb 1 100)) |
(fizzb 1 100)) |
||
(fizzbuzz)</ |
(fizzbuzz)</syntaxhighlight> |
||
=={{header|XMIDAS}}== |
=={{header|XMIDAS}}== |
||
< |
<syntaxhighlight lang="xmidas">startmacro |
||
loop 100 count |
loop 100 count |
||
calc/quiet three ^count 3 modulo |
calc/quiet three ^count 3 modulo |
||
Line 10,750: | Line 10,750: | ||
endif |
endif |
||
endloop |
endloop |
||
endmacro</ |
endmacro</syntaxhighlight> |
||
=={{header|Xojo}}== |
=={{header|Xojo}}== |
||
< |
<syntaxhighlight lang="vb"> For i As Integer = 1 To 100 |
||
If i Mod 3 = 0 And i Mod 5 = 0 Then |
If i Mod 3 = 0 And i Mod 5 = 0 Then |
||
Print("FizzBuzz") |
Print("FizzBuzz") |
||
Line 10,763: | Line 10,763: | ||
Print(Str(i)) |
Print(Str(i)) |
||
End If |
End If |
||
Next</ |
Next</syntaxhighlight> |
||
An alternative syntax: |
An alternative syntax: |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
For i As Integer = 1 To 100 |
For i As Integer = 1 To 100 |
||
Select Case True |
Select Case True |
||
Line 10,777: | Line 10,777: | ||
Print(Str(i)) |
Print(Str(i)) |
||
End Select |
End Select |
||
Next</ |
Next</syntaxhighlight> |
||
=={{header|XPath 2.0}}== |
=={{header|XPath 2.0}}== |
||
< |
<syntaxhighlight lang="xpath">for $n in 1 to 100 return |
||
concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])</ |
concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])</syntaxhighlight> |
||
...or alternatively... |
...or alternatively... |
||
< |
<syntaxhighlight lang="xpath">for $n in 1 to 100 return |
||
($n, 'Fizz', 'Buzz', 'FizzBuzz')[number(($n mod 3) = 0) + number(($n mod 5) = 0)*2 + 1]</ |
($n, 'Fizz', 'Buzz', 'FizzBuzz')[number(($n mod 3) = 0) + number(($n mod 5) = 0)*2 + 1]</syntaxhighlight> |
||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code CrLf=9, IntOut=11, Text=12; |
||
int N; |
int N; |
||
[for N:= 1 to 100 do |
[for N:= 1 to 100 do |
||
Line 10,795: | Line 10,795: | ||
CrLf(0); |
CrLf(0); |
||
]; |
]; |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 10,823: | Line 10,823: | ||
===XSLT 1.0=== |
===XSLT 1.0=== |
||
{{works with|xsltproc|libxslt 10126}} |
{{works with|xsltproc|libxslt 10126}} |
||
< |
<syntaxhighlight lang="xml"><?xml version="1.0" encoding="utf-8" ?> |
||
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> |
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> |
||
<xsl:output method="text" encoding="utf-8"/> |
<xsl:output method="text" encoding="utf-8"/> |
||
Line 10,875: | Line 10,875: | ||
<xsl:call-template name="fizzbuzz-range"/> |
<xsl:call-template name="fizzbuzz-range"/> |
||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet></ |
</xsl:stylesheet></syntaxhighlight> |
||
===XSLT 1.0 With EXSLT=== |
===XSLT 1.0 With EXSLT=== |
||
< |
<syntaxhighlight lang="xml"><xsl:stylesheet version="1.0" |
||
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" |
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" |
||
xmlns:exsl="http://exslt.org/common" |
xmlns:exsl="http://exslt.org/common" |
||
Line 10,909: | Line 10,909: | ||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet></ |
</xsl:stylesheet></syntaxhighlight> |
||
===XSLT 2.0=== |
===XSLT 2.0=== |
||
< |
<syntaxhighlight lang="xml"><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> |
||
<xsl:output method="text"/> |
<xsl:output method="text"/> |
||
Line 10,921: | Line 10,921: | ||
</xsl:template> |
</xsl:template> |
||
</xsl:stylesheet></ |
</xsl:stylesheet></syntaxhighlight> |
||
Line 10,930: | Line 10,930: | ||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
===Iterative solution=== |
===Iterative solution=== |
||
< |
<syntaxhighlight lang="yorick">for(i = 1; i <= 100; i++) { |
||
if(i % 3 == 0) |
if(i % 3 == 0) |
||
write, format="%s", "Fizz"; |
write, format="%s", "Fizz"; |
||
Line 10,938: | Line 10,938: | ||
write, format="%d", i; |
write, format="%d", i; |
||
write, ""; |
write, ""; |
||
}</ |
}</syntaxhighlight> |
||
===Vectorized solution=== |
===Vectorized solution=== |
||
< |
<syntaxhighlight lang="yorick">output = swrite(format="%d", indgen(100)); |
||
output(3::3) = "Fizz"; |
output(3::3) = "Fizz"; |
||
output(5::5) = "Buzz"; |
output(5::5) = "Buzz"; |
||
output(15::15) = "FizzBuzz"; |
output(15::15) = "FizzBuzz"; |
||
write, format="%s\n", output;</ |
write, format="%s\n", output;</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
Line 10,950: | Line 10,950: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">foreach n in ([1..100]) { |
||
if(n % 3 == 0) print("Fizz"); |
if(n % 3 == 0) print("Fizz"); |
||
if(not (n%5)) "Buzz".print(); |
if(not (n%5)) "Buzz".print(); |
||
if(n%3 and n%5) print(n); |
if(n%3 and n%5) print(n); |
||
println(); |
println(); |
||
}</ |
}</syntaxhighlight> |
||
Or, using infinite lazy sequences: |
Or, using infinite lazy sequences: |
||
< |
<syntaxhighlight lang="zkl">fcn f(a,b,c){ a+b and a+b or c } |
||
Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..]) |
Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..]) |
||
.walk(100).concat("\n").println();</ |
.walk(100).concat("\n").println();</syntaxhighlight> |
||
More of the same: |
More of the same: |
||
< |
<syntaxhighlight lang="zkl">Walker.cycle(0,0,"Fizz",0,"Buzz","Fizz",0,0,"Fizz","Buzz",0,"Fizz",0,0,"FizzBuzz") |
||
.zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println();</ |
.zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println();</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 10,985: | Line 10,985: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
{{trans|Applesoft BASIC}} |
{{trans|Applesoft BASIC}} |
||
< |
<syntaxhighlight lang="zxbasic">10 DEF FN m(a,b)=a-INT (a/b)*b |
||
20 FOR a=1 TO 100 |
20 FOR a=1 TO 100 |
||
30 LET o$="" |
30 LET o$="" |
||
Line 10,992: | Line 10,992: | ||
60 IF o$="" THEN LET o$=STR$ a |
60 IF o$="" THEN LET o$=STR$ a |
||
70 PRINT o$ |
70 PRINT o$ |
||
80 NEXT a</ |
80 NEXT a</syntaxhighlight> |
Revision as of 13:20, 27 August 2022
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
- for multiples of three, print Fizz (instead of the number)
- for multiples of five, print Buzz (instead of the number)
- for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
- Also see
- (a blog) dont-overthink-fizzbuzz
- (a blog) fizzbuzz-the-programmers-stairway-to-heaven
11l
L(i) 1..100
I i % 15 == 0
print(‘FizzBuzz’)
E I i % 3 == 0
print(‘Fizz’)
E I i % 5 == 0
print(‘Buzz’)
E
print(i)
360 Assembly
6502 Assembly
68000 Assembly
8080 Assembly
8086 Assembly
8th
with: n
: num? \ n f -- )
if drop else . then ;
\ is m mod n 0? leave the result twice on the stack
: div? \ m n -- f f
mod 0 = dup ;
: fizz? \ n -- n f
dup 3
div? if "Fizz" . then ;
: buzz? \ n f -- n f
over 5
div? if "Buzz" . then or ;
\ print a message as appropriate for the given number:
: fizzbuzz \ n --
fizz? buzz? num?
space ;
\ iterate from 1 to 100:
' fizzbuzz 1 100 loop
cr bye
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program FizzBuzz64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessFizz: .asciz "Fizz\n"
szMessBuzz: .asciz "Buzz\n"
szMessFizzBuzz: .asciz "FizzBuzz\n"
szMessNumber: .asciz "Number : @ "
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneConv: .skip 24
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
mov x10,3 // divisor 3
mov x11,5 // divisor 5
mov x12,15 // divisor 15
mov x13,1 // indice
1: // loop begin
udiv x14,x13,x12 // multiple 15
msub x15,x14,x12,x13 // remainder
cbnz x15,2f // zero ?
mov x0,x13
ldr x1,qAdrszMessFizzBuzz
bl displayResult
b 4f
2: // multiple 3
udiv x14,x13,x10
msub x15,x14,x10,x13 // remainder
cbnz x15,3f // zero ?
mov x0,x13
ldr x1,qAdrszMessFizz
bl displayResult
b 4f
3: // multiple 5
udiv x14,x13,x11
msub x15,x14,x11,x13 // remainder
cbnz x15,4f // zero ?
mov x0,x13
ldr x1,qAdrszMessBuzz
bl displayResult
4:
add x13,x13,1 // increment indice
cmp x13,100 // maxi ?
ble 1b
100: // standard end of the program
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessFizzBuzz: .quad szMessFizzBuzz
qAdrszMessFizz: .quad szMessFizz
qAdrszMessBuzz: .quad szMessBuzz
/******************************************************************/
/* Display résult */
/******************************************************************/
/* x0 contains the number*/
/* x1 contains display string address */
displayResult:
stp x2,lr,[sp,-16]! // save registers
mov x2,x1
ldr x1,qAdrsZoneConv // conversion number
bl conversion10S // decimal conversion
ldr x0,qAdrszMessNumber
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message final
mov x0,x2
bl affichageMess
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
qAdrszMessNumber: .quad szMessNumber
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
ABAP
Impure Functional 1
DATA: tab TYPE TABLE OF string.
tab = VALUE #(
FOR i = 1 WHILE i <= 100 (
COND string( LET r3 = i MOD 3
r5 = i MOD 5 IN
WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|
WHEN r3 = 0 THEN |FIZZ|
WHEN r5 = 0 THEN |BUZZ|
ELSE i ) ) ).
cl_demo_output=>write( tab ).
cl_demo_output=>display( ).
Impure Functional 2
cl_demo_output=>display( value stringtab( for i = 1 until i > 100
let fizz = cond #( when i mod 3 = 0 then |fizz| else space )
buzz = cond #( when i mod 5 = 0 then |buzz| else space )
fb = |{ fizz }{ buzz }| in
( switch #( fb when space then i else fb ) ) ) ).
ACL2
(defun fizzbuzz-r (i)
(declare (xargs :measure (nfix (- 100 i))))
(prog2$
(cond ((= (mod i 15) 0) (cw "FizzBuzz~%"))
((= (mod i 5) 0) (cw "Buzz~%"))
((= (mod i 3) 0) (cw "Fizz~%"))
(t (cw "~x0~%" i)))
(if (zp (- 100 i))
nil
(fizzbuzz-r (1+ i)))))
(defun fizzbuzz () (fizzbuzz-r 1))
Action!
PROC Main()
BYTE i,d3,d5
d3=1 d5=1
FOR i=1 TO 100
DO
IF d3=0 AND d5=0 THEN
Print("FizzBuzz")
ELSEIF d3=0 THEN
Print("Fizz")
ELSEIF d5=0 THEN
Print("Buzz")
ELSE
PrintB(i)
FI
Put(32)
d3==+1 d5==+1
IF d3=3 THEN d3=0 FI
IF d5=5 THEN d5=0 FI
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
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
ActionScript
The ActionScript solution works just like the JavaScript solution (they share the ECMAScript specification). The difference is that ActionScript has the trace command to write out to a console.
for (var i:int = 1; i <= 100; i++) {
if (i % 15 == 0)
trace('FizzBuzz');
else if (i % 5 == 0)
trace('Buzz');
else if (i % 3 == 0)
trace('Fizz');
else
trace(i);
}
Ada
with Ada.Text_IO; use Ada.Text_IO;
procedure Fizzbuzz is
begin
for I in 1..100 loop
if I mod 15 = 0 then
Put_Line("FizzBuzz");
elsif I mod 5 = 0 then
Put_Line("Buzz");
elsif I mod 3 = 0 then
Put_Line("Fizz");
else
Put_Line(Integer'Image(I));
end if;
end loop;
end Fizzbuzz;
ALGOL 68
main:(
FOR i TO 100 DO
printf(($gl$,
IF i %* 15 = 0 THEN
"FizzBuzz"
ELIF i %* 3 = 0 THEN
"Fizz"
ELIF i %* 5 = 0 THEN
"Buzz"
ELSE
i
FI
))
OD
)
or simply:
FOR i TO 100 DO print(((i%*15=0|"FizzBuzz"|:i%*3=0|"Fizz"|:i%*5=0|"Buzz"|i),new line)) OD
ALGOL-M
BEGIN
INTEGER FUNCTION DIVBY(N, D);
INTEGER N;
INTEGER D;
BEGIN
DIVBY := 1 - (N - D * (N / D));
END;
INTEGER I;
FOR I := 1 STEP 1 UNTIL 100 DO
BEGIN
IF DIVBY(I, 15) = 1 THEN
WRITE("FizzBuzz")
ELSE IF DIVBY(I, 5) = 1 THEN
WRITE("Buzz")
ELSE IF DIVBY(I, 3) = 1 THEN
WRITE("Fizz")
ELSE
WRITE(I);
END;
END
ALGOL W
begin
i_w := 1; % set integers to print in minimum space %
for i := 1 until 100 do begin
if i rem 15 = 0 then write( "FizzBuzz" )
else if i rem 5 = 0 then write( "Buzz" )
else if i rem 3 = 0 then write( "Fizz" )
else write( i )
end for_i
end.
AntLang
n:{1+ x}map range[100]
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n
echo map s
APEX
for(integer i=1; i <= 100; i++){
String output = '';
if(math.mod(i, 3) == 0) output += 'Fizz';
if(math.mod(i, 5) == 0) output += 'Buzz';
if(output != ''){
System.debug(output);
} else {
System.debug(i);
}
}
APL
⎕IO←0
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]
Slightly different approach that makes use of the Decode function (⊥):
A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100]
The idea is to first calculate the residues for all numbers 1..100 after division with both 3 and 5. This generates 100 pairs of numbers a b, where a is either 0,1,2 and b is either 0,1,2,3,4.
These pairs are then put through the sign function which returns 0 for a 0, and a 1 for anything greater than 0. Now we have binary pairs. The binary pairs are encoded with a left argument of 2 resulting in 0,1,2,3. These are treated as indices for the "FizzBuzz vector" where 0 is in position 3.
Variable A holds this new vector of words and zeros. Variable I is assigned the zeros' positions. Finally A[I] is replaced with corresponding indices.
If you have an aversion against mixed vectors, consider inserting ⍕¨ before the final (i.e. left-most) assignment.
Here's a Dyalog-specific solution taking advantage of its anonymous function extension:
{ ⍵ 'Fizz' 'Buzz' 'FizzBuzz'[ +/1 2×0=3 5|⍵] }¨1+⍳100
A slightly different version that works both in Dyalog and GNU APL -- credit to Aniket Bhattacharyea, posted on codeburst.io (https://codeburst.io/fizzbuzz-in-apl-a193d1954b4b):
{(‘FizzBuzz’ ‘Fizz’ ‘Buzz’,⍵)[(0=15 3 5|⍵)⍳1]}¨⍳100
Yet another solution, excessively commented:
(and Dyalog, with ⎕ML ← 2)
∇ sv ← fizzbuzz n; t;d
[1] ⍝⍝ Solve the popular 'fizzbuzz' problem in APL.
[2] ⍝⍝ \param n - highest number to compute (≥0)
[3] ⍝⍝ \returns sv - a vector of strings representing the fizzbuzz solution for ⍳n
[4] ⍝⍝ (note we return a string vector to avoid a mixed-type result; remove the
[5] ⍝⍝ ⍕ function from the (⍕t[⍵]) term to see the difference).
[6] ⍝⍝⍝⍝
[7] t←⍳n ⍝ the sequence 1..n itself which we'll pick from
[8] ⍝ ... or the words 'fizz', 'buzz', 'fizzbuzz' depending on
[9] ⍝ ... divisibility by 3 and/or 5
[10] ⍝⎕←t ⍝ (Uncomment to see during call)
[11]
[12] d←1+(+⌿ ⊃ {((0=3|⍵)) (2×(0=5|⍵))} ⍳n)
[13] ⍝ || || | | | ↓↓
[14] ⍝ || || | | | ⍳n: generate range (1..n)
[15] ⍝ || || | ↓.....................↓ ↓↓
[16] ⍝ || || | A dfn (lambda) taking its right arg (⍵, ⍳n here) to compute two boolean
[17] ⍝ || || | vectors(v12): divisibility by 3 and 5, respectively, for each of ⍳n
[18] ⍝ || || ↓
[19] ⍝ || || ⊃: Disclose ('lift-up' and pad w/zeros) the 'ragged' matrix of vectors (v12)
[20] ⍝ || || holding divisibility by 3 and 5 of each ⍳n
[21] ⍝ || ↓↓
[22] ⍝ || +⌿: Sum (v12) row-wise to count divisibility (0=neither 3 nor 5, 1=3, 2=3 and 5)
[23] ⍝ ↓↓
[24] ⍝ 1+: Add one to (v12) to make them 1-based for indexing below:
[25] ⍝⎕←d
[26]
[27] sv ← { ((⍕t[⍵]) 'Fizz' 'Buzz' 'FizzBuzz') [d[⍵]]}¨ ⍳n
[28] ⍝ | | | | | |
[29] ⍝ | | | ↓....↓ |
[30] ⍝ | |................................↓ idx |
[31] ⍝ | ( lookup output vector ) |
[32] ⍝ ↓...........................................↓
[33] ⍝ A dfn (lambda) taking as its right arg (⍵) ⍳n and using the 'each' (¨)
[34] ⍝ operator to apply the lambda to each (idx) of ⍳n.
[35]
[36] ⍝⍝ USAGE
[37] ⍝⍝ ⎕ ← ,fizzbuzz 15
[38] ⍝ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
∇
AppleScript
Procedural
property outputText: ""
repeat with i from 1 to 100
if i mod 15 = 0 then
set outputText to outputText & "FizzBuzz"
else if i mod 3 = 0 then
set outputText to outputText & "Fizz"
else if i mod 5 = 0 then
set outputText to outputText & "Buzz"
else
set outputText to outputText & i
end if
set outputText to outputText & linefeed
end repeat
outputText
If this were a useful task requiring a degree of efficiency, it would be better to replace the cumulative text concatenations with additions to a fast-to-access list and coerce this list to text in one go at the end. Less critically, the (i mod … = 0) tests could be nested to reduce the number of these performed from 261 to 200:
on fizzBuzz(n)
script o
property output : {}
end script
repeat with i from 1 to n
if (i mod 3 = 0) then
if (i mod 15 = 0) then
set end of o's output to "FizzBuzz"
else
set end of o's output to "Fizz"
end if
else if (i mod 5 = 0) then
set end of o's output to "Buzz"
else
set end of o's output to i
end if
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to o's output as text
set AppleScript's text item delimiters to astid
return output
end fizzBuzz
fizzBuzz(100)
Another alternative would be simply to fill the list with numbers and then go through it again three times overwriting the relevant slots with the appropriate words:
on fizzBuzz(n)
script o
property output : {}
end script
repeat with i from 1 to n
set end of o's output to i
end repeat
repeat with x in {{3, "Fizz"}, {5, "Buzz"}, {15, "FizzBuzz"}}
set {m, t} to x
repeat with i from m to n by m
set item i of o's output to t
end repeat
end repeat
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to linefeed
set output to o's output as text
set AppleScript's text item delimiters to astid
return output
end fizzBuzz
fizzBuzz(100)
With the number of numbers raised from 100 to 10,000, the two scripts inserted here take around 0.051 seconds to execute on my current machine, the original AppleScript above around 0.25 seconds, and the one below (originally described as "functional composition") 3.52 seconds.
Functional
For simplicity, and more efficient use of the scripter's time:
------------------------- FIZZBUZZ -------------------------
-- fizz :: Int -> Bool
on fizz(n)
n mod 3 = 0
end fizz
-- buzz :: Int -> Bool
on buzz(n)
n mod 5 = 0
end buzz
-- fizzAndBuzz :: Int -> Bool
on fizzAndBuzz(n)
n mod 15 = 0
end fizzAndBuzz
-- fizzBuzz :: Int -> String
on fizzBuzz(x)
caseOf(x, [[my fizzAndBuzz, "FizzBuzz"], ¬
[my fizz, "Fizz"], ¬
[my buzz, "Buzz"]], x as string)
end fizzBuzz
--------------------------- TEST ---------------------------
on run
intercalate(linefeed, ¬
map(fizzBuzz, enumFromTo(1, 100)))
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- caseOf :: a -> [(predicate, b)] -> Maybe b -> Maybe b
on caseOf(e, lstPV, default)
repeat with lstCase in lstPV
set {p, v} to contents of lstCase
if mReturn(p)'s |λ|(e) then return v
end repeat
return default
end caseOf
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
Applesoft BASIC
See FizzBuzz/Basic
Arbre
fizzbuzz():
for x in [1..100]
if x%5==0 and x%3==0
return "FizzBuzz"
else
if x%3==0
return "Fizz"
else
if x%5==0
return "Buzz"
else
return x
main():
fizzbuzz() -> io
Arc
Arc 3.1 Base
(for n 1 100
(prn:if
(multiple n 15) 'FizzBuzz
(multiple n 5) 'Buzz
(multiple n 3) 'Fizz
n))
(for n 1 100
(prn:check (string (when (multiple n 3) 'Fizz)
(when (multiple n 5) 'Buzz))
~empty n)) ; check created string not empty, else return n
Waterhouse Arc
(for n 1 100
(prn:case (gcd n 15)
1 n
3 'Fizz
5 'Buzz
'FizzBuzz))
ARM Assembly
/ * linux GAS */
.global _start
.data
Fizz: .ascii "Fizz\n"
Buzz: .ascii "Buzz\n"
FizzAndBuzz: .ascii "FizzBuzz\n"
numstr_buffer: .skip 3
newLine: .ascii "\n"
.text
_start:
bl FizzBuzz
mov r7, #1
mov r0, #0
svc #0
FizzBuzz:
push {lr}
mov r9, #100
fizzbuzz_loop:
mov r0, r9
mov r1, #15
bl divide
cmp r1, #0
ldreq r1, =FizzAndBuzz
moveq r2, #9
beq fizzbuzz_print
mov r0, r9
mov r1, #3
bl divide
cmp r1, #0
ldreq r1, =Fizz
moveq r2, #5
beq fizzbuzz_print
mov r0, r9
mov r1, #5
bl divide
cmp r1, #0
ldreq r1, =Buzz
moveq r2, #5
beq fizzbuzz_print
mov r0, r9
bl make_num
mov r2, r1
mov r1, r0
fizzbuzz_print:
mov r0, #1
mov r7, #4
svc #0
sub r9, #1
cmp r9, #0
bgt fizzbuzz_loop
pop {lr}
mov pc, lr
make_num:
push {lr}
ldr r4, =numstr_buffer
mov r5, #4
mov r6, #1
mov r1, #100
bl divide
cmp r0, #0
subeq r5, #1
movne r6, #0
add r0, #48
strb r0, [r4, #0]
mov r0, r1
mov r1, #10
bl divide
cmp r0, #0
movne r6, #0
cmp r6, #1
subeq r5, #1
add r0, #48
strb r0, [r4, #1]
add r1, #48
strb r1, [r4, #2]
mov r2, #4
sub r0, r2, r5
add r0, r4, r0
mov r1, r5
pop {lr}
mov pc, lr
divide:
udiv r2, r0, r1
mul r3, r1, r2
sub r1, r0, r3
mov r0, r2
mov pc, lr
Arturo
loop 1..100 [x][
case []
when? [0=x%15] -> print "FizzBuzz"
when? [0=x%3] -> print "Fizz"
when? [0=x%5] -> print "Buzz"
else -> print x
]
- Output:
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
AsciiDots
See FizzBuzz/EsoLang#AsciiDots
ASIC
See FizzBuzz/Basic
Asymptote
for(int number = 1; number <= 100; ++number) {
if (number % 15 == 0) {
write("FizzBuzz");
} else {
if (number % 3 == 0) {
write("Fizz");
} else {
if (number % 5 == 0) {
write("Buzz");
} else {
write(number);
}
}
}
}
ATS
#include "share/atspre_staload.hats"
implement main0() = loop(1, 100) where {
fun loop(from: int, to: int): void =
if from > to then () else
let
val by3 = (from % 3 = 0)
val by5 = (from % 5 = 0)
in
case+ (by3, by5) of
| (true, true) => print_string("FizzBuzz")
| (true, false) => print_string("Fizz")
| (false, true) => print_string("Buzz")
| (false, false) => print_int(from);
print_newline();
loop(from+1, to)
end
}
AutoHotkey
Search autohotkey.com: [1]
Loop, 100
{
If (Mod(A_Index, 15) = 0)
output .= "FizzBuzz`n"
Else If (Mod(A_Index, 3) = 0)
output .= "Fizz`n"
Else If (Mod(A_Index, 5) = 0)
output .= "Buzz`n"
Else
output .= A_Index "`n"
}
FileDelete, output.txt
FileAppend, %output%, output.txt
Run, cmd /k type output.txt
A short example with cascading ternary operators and graphical output. Press Esc to close the window.
Gui, Add, Edit, r20
Gui,Show
Loop, 100
Send, % (!Mod(A_Index, 15) ? "FizzBuzz" : !Mod(A_Index, 3) ? "Fizz" : !Mod(A_Index, 5) ? "Buzz" : A_Index) "`n"
Return
Esc::
ExitApp
AutoIt
Example1
Output via MsgBox():
For $i = 1 To 100
If Mod($i, 15) = 0 Then
MsgBox(0, "FizzBuzz", "FizzBuzz")
ElseIf Mod($i, 5) = 0 Then
MsgBox(0, "FizzBuzz", "Buzz")
ElseIf Mod($i, 3) = 0 Then
MsgBox(0, "FizzBuzz", "Fizz")
Else
MsgBox(0, "FizzBuzz", $i)
EndIf
Next
Example2
Output via console, logfile and/or messagebox:
#include <Constants.au3>
; uncomment how you want to do the output
Func Out($Msg)
ConsoleWrite($Msg & @CRLF)
;~ FileWriteLine("FizzBuzz.Log", $Msg)
;~ $Btn = MsgBox($MB_OKCANCEL + $MB_ICONINFORMATION, "FizzBuzz", $Msg)
;~ If $Btn > 1 Then Exit ; Pressing 'Cancel'-button aborts the program
EndFunc ;==>Out
Out("# FizzBuzz:")
For $i = 1 To 100
If Mod($i, 15) = 0 Then
Out("FizzBuzz")
ElseIf Mod($i, 5) = 0 Then
Out("Buzz")
ElseIf Mod($i, 3) = 0 Then
Out("Fizz")
Else
Out($i)
EndIf
Next
Out("# Done.")
Avail
For each i from 1 to 100 do [
Print:
if i mod 15 = 0 then ["FizzBuzz"]
else if i mod 3 = 0 then ["Fizz"]
else if i mod 5 = 0 then ["Buzz"]
else [“i”]
++ "\n";
];
AWK
See FizzBuzz/AWK
Axe
For(I,1,100)
!If I^3??I^5
Disp "FIZZBUZZ",i
Else!If I^3
Disp "FIZZ",i
Else!If I^5
Disp "BUZZ",i
Else
Disp I▶Dec,i
End
.Pause to allow the user to actually read the output
Pause 1000
End
Babel
main:
{ { iter 1 + dup
15 %
{ "FizzBuzz" <<
zap }
{ dup
3 %
{ "Fizz" <<
zap }
{ dup
5 %
{ "Buzz" <<
zap}
{ %d << }
if }
if }
if
"\n" << }
100 times }
BaCon
bash
Any bash hacker would do this as a one liner at the shell, so...
for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n; done
For the sake of readability...
for n in {1..100}; do
((( n % 15 == 0 )) && echo 'FizzBuzz') ||
((( n % 5 == 0 )) && echo 'Buzz') ||
((( n % 3 == 0 )) && echo 'Fizz') ||
echo $n;
done
Here's a very concise approach, with only 75 characters total. Unfortunately it relies on aspects of Bash which are rarely used.
for i in {1..100};do((i%3))&&x=||x=Fizz;((i%5))||x+=Buzz;echo ${x:-$i};done
Here's the concise approach again, this time separated into multiple lines.
# FizzBuzz in Bash. A concise version, but with verbose comments.
for i in {1..100} # Use i to loop from "1" to "100", inclusive.
do ((i % 3)) && # If i is not divisible by 3...
x= || # ...blank out x (yes, "x= " does that). Otherwise,...
x=Fizz # ...set (not append) x to the string "Fizz".
((i % 5)) || # If i is not divisible by 5, skip (there's no "&&")...
x+=Buzz # ...Otherwise, append (not set) the string "Buzz" to x.
echo ${x:-$i} # Print x unless it is blanked out. Otherwise, print i.
done
It's a bit silly to optimize such a small & fast program, but for the sake of algorithm analysis it's worth noting that the concise approach is reasonably efficient in several ways. Each divisibility test appears in the code exactly once, only two variables are created, and the approach avoids setting variables unnecessarily. As far as I can tell, the divisibility tests only fire the minimum number of times required for the general case (e.g. where the 100/3/5 constants can be changed), unless you introduce more variables and test types. Corrections invited. I avoided analyzing the non-general case where 100/3/5 never change, because one "optimal" solution is to simply print the pre-computed answer,
BASIC
See FizzBuzz/Basic
BASIC256
See FizzBuzz/Basic
Batch File
FOR /L version:
@echo off
for /L %%i in (1,1,100) do call :tester %%i
goto :eof
:tester
set /a test = %1 %% 15
if %test% NEQ 0 goto :NotFizzBuzz
echo FizzBuzz
goto :eof
:NotFizzBuzz
set /a test = %1 %% 5
if %test% NEQ 0 goto :NotBuzz
echo Buzz
goto :eof
:NotBuzz
set /a test = %1 %% 3
if %test% NEQ 0 goto :NotFizz
echo Fizz
goto :eof
:NotFizz
echo %1
Loop version:
@echo off
set n=1
:loop
call :tester %n%
set /a n += 1
if %n% LSS 101 goto loop
goto :eof
:tester
set /a test = %1 %% 15
if %test% NEQ 0 goto :NotFizzBuzz
echo FizzBuzz
goto :eof
:NotFizzBuzz
set /a test = %1 %% 5
if %test% NEQ 0 goto :NotBuzz
echo Buzz
goto :eof
:NotBuzz
set /a test = %1 %% 3
if %test% NEQ 0 goto :NotFizz
echo Fizz
goto :eof
:NotFizz
echo %1
FOR /L with a block instead of very-high-overhead subroutine call:
@echo off & setlocal enabledelayedexpansion
for /l %%i in (1,1,100) do (
set /a m5=%%i %% 5
set /a m3=%%i %% 3
set s=
if !m5! equ 0 set s=!s!Fizz
if !m3! equ 0 set s=!s!Buzz
if "!s!"=="" set s=%%i
echo !s!
)
BBC BASIC
See FizzBuzz/Basic
bc
This solution never uses else, because bc has no else keyword (but some implementations add else as an extension).
for (i = 1; i <= 100; i++) {
w = 0
if (i % 3 == 0) { "Fizz"; w = 1; }
if (i % 5 == 0) { "Buzz"; w = 1; }
if (w == 0) i
if (w == 1) "
"
}
quit
BCPL
GET "libhdr"
LET start() BE $(
FOR i=1 TO 100 DO $(
TEST (i REM 15) = 0 THEN
writes("FizzBuzz")
ELSE TEST (i REM 3) = 0 THEN
writes("Fizz")
ELSE TEST (i REM 5) = 0 THEN
writes("Buzz")
ELSE
writen(i, 0)
newline()
$)
$)
beeswax
Also see on FizzBuzz/EsoLang
“Ordinary” FizzBuzz solution:
> q
>@F5~%"d@F{ > @F q
_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp
;bL@~.~4~.5~5@ P<
Example without double mod 5 check, using a flag instead, to check if Fizz already got printed (in this case the number n must not be printed if mod 5 is > 0):
>@?q
> q >Ag'd@{?p
_>"1F3~%'d`Fizz`f>@F5~%'d`Buzz`@p
b P~;"-~@~.+0~P9@N?<
Befunge
See FizzBuzz/EsoLang
blz
for i = 0; i <= 100; i++
out = ""
if i % 3 == 0
out = "Fizz"
end
if i % 5 == 0
out = out + "Buzz"
end
if out == ""
out = i
end
print(out)
end
Boo
def fizzbuzz(size):
for i in range(1, size):
if i%15 == 0:
print 'FizzBuzz'
elif i%5 == 0:
print 'Buzz'
elif i%3 == 0:
print 'Fizz'
else:
print i
fizzbuzz(101)
BQN
(∾´∾⟜"Fizz"‿"Buzz"/˜·(¬∨´)⊸∾0=3‿5|⊢)¨1+↕100
Bracmat
0:?i&whl'(1+!i:<101:?i&out$(mod$(!i.3):0&(mod$(!i.5):0&FizzBuzz|Fizz)|mod$(!i.5):0&Buzz|!i))
Same code, pretty printed:
0:?i
& whl
' ( 1+!i:<101:?i
& out
$ ( mod$(!i.3):0
& ( mod$(!i.5):0&FizzBuzz
| Fizz
)
| mod$(!i.5):0&Buzz
| !i
)
)
Brainf***
See FizzBuzz/EsoLang
Brat
1.to 100 { n |
true? n % 15 == 0
{ p "FizzBuzz" }
{ true? n % 3 == 0
{ p "Fizz" }
{ true? n % 5 == 0
{ p "Buzz" }
{ p n }
}
}
}
BrightScript (for Roku)
FOR i = 1 TO 100
fz = i MOD 3 = 0
bz = i MOD 5 = 0
IF fz OR bz
IF fz AND NOT bz: str = "Fizz"
ELSEIF bz AND NOT fz: str = "Buzz"
ELSE str = "FizzBuzz"
END IF
ELSE
str = i.ToStr()
END IF
? str
END FOR
C
For 2 prime numbers and based on a similar minimal JavaScript solution with low signal-to-noise, the C code is:
int i = 0 ; char B[88] ;
while ( i++ < 100 )
!sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" )
? sprintf( B, "%d", i ):0, printf( ", %s", B );
With 4 prime numbers:
int i = 0 ; char B[88] ;
while ( i++ < 100 )
!sprintf( B, "%s%s%s%s",
i%3 ? "":"Fiz", i%5 ? "":"Buz", i%7 ? "":"Goz", i%11 ? "":"Kaz" )
? sprintf( B, "%d", i ):0, printf( ", %s", B );
Output: ..., 89, FizBuz, Goz, 92, Fiz, 94, Buz, Fiz, 97, Goz, FizKaz, Buz
One line version, with pretty printing
#include <stdio.h>
int main() {
for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n");
}
This actually works (the array init part, saves 6 bytes of static data, whee):
#include<stdio.h>
int main ()
{
int i;
const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" };
for (i = 1; i <= 100; i++)
printf(s[!(i % 3) + 2 * !(i % 5)], i);
return 0;
}
#include<stdio.h>
int main (void)
{
int i;
for (i = 1; i <= 100; i++)
{
if (!(i % 15))
printf ("FizzBuzz");
else if (!(i % 3))
printf ("Fizz");
else if (!(i % 5))
printf ("Buzz");
else
printf ("%d", i);
printf("\n");
}
return 0;
}
Implicit int main and return 0 (C99+):
#include <stdio.h>
main() {
int i = 1;
while(i <= 100) {
if(i % 15 == 0)
puts("FizzBuzz");
else if(i % 3 == 0)
puts("Fizz");
else if(i % 5 == 0)
puts("Buzz");
else
printf("%d\n", i);
i++;
}
}
obfuscated:
#include <stdio.h>
#define F(x,y) printf("%s",i%x?"":#y"zz")
int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;}
With numbers theory:
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 100; ++i) {
if (i % 3 == 0) printf("fizz");
if (i % 5 == 0) printf("buzz");
if (i * i * i * i % 15 == 1) printf("%d", i);
puts("");
}
}
Without conditionals, anything in the loop body gcc compiles with branching, duplicate tests or duplicate strings. Depends on ASCII and two's complement arithmetic:
#include <stdio.h>
int main()
{
for (int i=0;++i<101;puts(""))
{
char f[] = "FizzBuzz%d";
f[8-i%5&12]=0;
printf (f+(-i%3&4+f[8]/8), i);
}
}
C#
class Program
{
public void FizzBuzzGo()
{
Boolean Fizz = false;
Boolean Buzz = false;
for (int count = 1; count <= 100; count ++)
{
Fizz = count % 3 == 0;
Buzz = count % 5 == 0;
if (Fizz && Buzz)
{
Console.WriteLine("Fizz Buzz");
listBox1.Items.Add("Fizz Buzz");
}
else if (Fizz)
{
Console.WriteLine("Fizz");
listBox1.Items.Add("Fizz");
}
else if (Buzz)
{
Console.WriteLine("Buzz");
listBox1.Items.Add("Buzz");
}
else
{
Console.WriteLine(count);
listBox1.Items.Add(count);
}
}
}
}
class Program
{
static void Main()
{
for (uint i = 1; i <= 100; i++)
{
string s = null;
if (i % 3 == 0)
s = "Fizz";
if (i % 5 == 0)
s += "Buzz";
System.Console.WriteLine(s ?? i.ToString());
}
}
}
using System;
using System.Linq;
namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
Enumerable.Range(1, 100)
.Select(a => String.Format("{0}{1}", a % 3 == 0 ? "Fizz" : string.Empty, a % 5 == 0 ? "Buzz" : string.Empty))
.Select((b, i) => String.IsNullOrEmpty(b) ? (i + 1).ToString() : b)
.ToList()
.ForEach(Console.WriteLine);
}
}
}
using System;
using System.Globalization;
using System.Linq;
namespace FizzBuzz
{
class Program
{
static void Main()
{
Enumerable.Range(1, 100)
.GroupBy(e => e % 15 == 0 ? "FizzBuzz" : e % 5 == 0 ? "Buzz" : e % 3 == 0 ? "Fizz" : string.Empty)
.SelectMany(item => item.Select(x => new {
Value = x,
Display = String.IsNullOrEmpty(item.Key) ? x.ToString(CultureInfo.InvariantCulture) : item.Key
}))
.OrderBy(x => x.Value)
.Select(x => x.Display)
.ToList()
.ForEach(Console.WriteLine);
}
}
}
using System;
namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
if (i % 15 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i);
}
}
}
}
}
using System;
using System.Globalization;
namespace Rosettacode
{
class Program
{
static void Main()
{
for (var number = 0; number < 100; number++)
{
if ((number % 3) == 0 & (number % 5) == 0)
{
//For numbers which are multiples of both three and five print "FizzBuzz".
Console.WriteLine("FizzBuzz");
continue;
}
if ((number % 3) == 0) Console.WriteLine("Fizz");
if ((number % 5) == 0) Console.WriteLine("Buzz");
if ((number % 3) != 0 && (number % 5) != 0) Console.WriteLine(number.ToString(CultureInfo.InvariantCulture));
if (number % 5 == 0)
{
Console.WriteLine(Environment.NewLine);
}
}
}
}
}
using System;
using System.Linq;
namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(i % 5 == 0 ? string.Format(i % 3 == 0 ? "Fizz{0}" : "{0}", "Buzz") : string.Format(i%3 == 0 ? "Fizz" : i.ToString())));
}
}
}
With C#8 switch expressions
class Program
{
public static string FizzBuzzIt(int n) =>
(n % 3, n % 5) switch
{
(0, 0) => "FizzBuzz",
(0, _) => "Fizz",
(_, 0) => "Buzz",
(_, _) => $"{n}"
};
static void Main(string[] args)
{
foreach (var n in Enumerable.Range(1, 100))
{
Console.WriteLine(FizzBuzzIt(n));
}
}
}
TDD using delegates
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FizzBuzz
{
[TestClass]
public class FizzBuzzTest
{
private FizzBuzz fizzBuzzer;
[TestInitialize]
public void Initialize()
{
fizzBuzzer = new FizzBuzz();
}
[TestMethod]
public void Give4WillReturn4()
{
Assert.AreEqual("4", fizzBuzzer.FizzBuzzer(4));
}
[TestMethod]
public void Give9WillReturnFizz()
{
Assert.AreEqual("Fizz", fizzBuzzer.FizzBuzzer(9));
}
[TestMethod]
public void Give25WillReturnBuzz()
{
Assert.AreEqual("Buzz", fizzBuzzer.FizzBuzzer(25));
}
[TestMethod]
public void Give30WillReturnFizzBuzz()
{
Assert.AreEqual("FizzBuzz", fizzBuzzer.FizzBuzzer(30));
}
[TestMethod]
public void First15()
{
ICollection expected = new ArrayList
{"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"};
var actual = Enumerable.Range(1, 15).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();
CollectionAssert.AreEqual(expected, actual);
}
[TestMethod]
public void From1To100_ToShowHowToGet100()
{
const int expected = 100;
var actual = Enumerable.Range(1, 100).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();
Assert.AreEqual(expected, actual.Count);
}
}
public class FizzBuzz
{
private delegate string Xzzer(int value);
private readonly IList<Xzzer> _functions = new List<Xzzer>();
public FizzBuzz()
{
_functions.Add(x => x % 3 == 0 ? "Fizz" : "");
_functions.Add(x => x % 5 == 0 ? "Buzz" : "");
}
public string FizzBuzzer(int value)
{
var result = _functions.Aggregate(String.Empty, (current, function) => current + function.Invoke(value));
return String.IsNullOrEmpty(result) ? value.ToString(CultureInfo.InvariantCulture) : result;
}
}
}
Good old C ways
using System;
int max = 100;
for(int i=0;
++i<=max;
Console.WriteLine("{0}{1}{2}", i%3==0 ? "Fizz" : "", i%5==0 ? "Buzz" : "", i%3!=0 && i%5!=0 ? i.ToString() : "")
){}
C++
minimal conditions
#include <iostream>
#include <chrono>
int main()
{
int fizz = 0, buzz = 0, fizzbuzz = 0;
bool isFizz = false;
auto startTime = std::chrono::high_resolution_clock::now();
for (unsigned int i = 1; i <= 4000000000; i++) {
isFizz = false;
if (i % 3 == 0) {
isFizz = true;
fizz++;
}
if (i % 5 == 0) {
if (isFizz) {
fizz--;
fizzbuzz++;
}
else {
buzz++;
}
}
}
auto endTime = std::chrono::high_resolution_clock::now();
auto totalTime = endTime - startTime;
printf("\t fizz : %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\n", fizz, buzz, fizzbuzz, (totalTime / std::chrono::milliseconds(1)));
return 0;
}
with modulo
#include <iostream>
using namespace std;
int main ()
{
for (int i = 1; i <= 100; i++)
{
if ((i % 15) == 0)
cout << "FizzBuzz\n";
else if ((i % 3) == 0)
cout << "Fizz\n";
else if ((i % 5) == 0)
cout << "Buzz\n";
else
cout << i << "\n";
}
return 0;
}
without modulo 15
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i <= 100; ++i)
{
bool fizz = (i % 3) == 0;
bool buzz = (i % 5) == 0;
if (fizz)
cout << "Fizz";
if (buzz)
cout << "Buzz";
if (!fizz && !buzz)
cout << i;
cout << "\n";
}
return 0;
}
without modulo
Modulo can be expensive on some architectures.
#include <iostream>
int main()
{
int i, f = 2, b = 4;
for ( i = 1 ; i <= 100 ; ++i, --f, --b )
{
if ( f && b ) { std::cout << i; }
if ( !f ) { std::cout << "Fizz"; f = 3; }
if ( !b ) { std::cout << "Buzz"; b = 5; }
std::cout << std::endl;
}
return 0;
}
using std::transform
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
std::vector<int> range(100);
std::iota(range.begin(), range.end(), 1);
std::vector<std::string> values;
values.resize(range.size());
auto fizzbuzz = [](int i) -> std::string {
if ((i%15) == 0) return "FizzBuzz";
if ((i%5) == 0) return "Buzz";
if ((i%3) == 0) return "Fizz";
return std::to_string(i);
};
std::transform(range.begin(), range.end(), values.begin(), fizzbuzz);
for (auto& str: values) std::cout << str << std::endl;
return 0;
}
metaprogramming
Version computing FizzBuzz at compile time with metaprogramming:
#include <iostream>
template <int n, int m3, int m5>
struct fizzbuzz : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
fizzbuzz()
{ std::cout << n << std::endl; }
};
template <int n>
struct fizzbuzz<n, 0, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
fizzbuzz()
{ std::cout << "FizzBuzz" << std::endl; }
};
template <int n, int p>
struct fizzbuzz<n, 0, p> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
fizzbuzz()
{ std::cout << "Fizz" << std::endl; }
};
template <int n, int p>
struct fizzbuzz<n, p, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>
{
fizzbuzz()
{ std::cout << "Buzz" << std::endl; }
};
template <>
struct fizzbuzz<0,0,0>
{
fizzbuzz()
{ std::cout << 0 << std::endl; }
};
template <int n>
struct fb_run
{
fizzbuzz<n, n%3, n%5> fb;
};
int main()
{
fb_run<100> fb;
return 0;
}
hardcore templates
Compile with -ftemplate-depth-9000 -std=c++0x:
#include <iostream>
#include <string>
#include <cstdlib>
#include <boost/mpl/string.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/size_t.hpp>
using namespace std;
using namespace boost;
///////////////////////////////////////////////////////////////////////////////
// exponentiation calculations
template <int accum, int base, int exp> struct POWER_CORE : POWER_CORE<accum * base, base, exp - 1>{};
template <int accum, int base>
struct POWER_CORE<accum, base, 0>
{
enum : int { val = accum };
};
template <int base, int exp> struct POWER : POWER_CORE<1, base, exp>{};
///////////////////////////////////////////////////////////////////////////////
// # of digit calculations
template <int depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_CORE<depth + 1, i / 10>{};
template <int depth>
struct NUM_DIGITS_CORE<depth, 0>
{
enum : int { val = depth};
};
template <int i> struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{};
template <>
struct NUM_DIGITS<0>
{
enum : int { val = 1 };
};
///////////////////////////////////////////////////////////////////////////////
// Convert digit to character (1 -> '1')
template <int i>
struct DIGIT_TO_CHAR
{
enum : char{ val = i + 48 };
};
///////////////////////////////////////////////////////////////////////////////
// Find the digit at a given offset into a number of the form 0000000017
template <unsigned int i, int place> // place -> [0 .. 10]
struct DIGIT_AT
{
enum : char{ val = (i / POWER<10, place>::val) % 10 };
};
struct NULL_CHAR
{
enum : char{ val = '\0' };
};
///////////////////////////////////////////////////////////////////////////////
// Convert the digit at a given offset into a number of the form '0000000017' to a character
template <unsigned int i, int place> // place -> [0 .. 9]
struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT<i, place>::val >{};
///////////////////////////////////////////////////////////////////////////////
// Convert the digit at a given offset into a number of the form '17' to a character
// Template description, with specialization to generate null characters for out of range offsets
template <unsigned int i, int offset, int numDigits, bool inRange>
struct OFFSET_CHAR_CORE_CHECKED{};
template <unsigned int i, int offset, int numDigits>
struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, false> : NULL_CHAR{};
template <unsigned int i, int offset, int numDigits>
struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, true> : ALT_CHAR<i, (numDigits - offset) - 1 >{};
// Perform the range check and pass it on
template <unsigned int i, int offset, int numDigits>
struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, offset < numDigits>{};
// Calc the number of digits and pass it on
template <unsigned int i, int offset>
struct OFFSET_CHAR : OFFSET_CHAR_CORE<i, offset, NUM_DIGITS<i>::val>{};
///////////////////////////////////////////////////////////////////////////////
// Integer to char* template. Works on unsigned ints.
template <unsigned int i>
struct IntToStr
{
const static char str[];
typedef typename mpl::string<
OFFSET_CHAR<i, 0>::val,
OFFSET_CHAR<i, 1>::val,
OFFSET_CHAR<i, 2>::val,
OFFSET_CHAR<i, 3>::val,
OFFSET_CHAR<i, 4>::val,
OFFSET_CHAR<i, 5>::val,
/*OFFSET_CHAR<i, 6>::val,
OFFSET_CHAR<i, 7>::val,
OFFSET_CHAR<i, 8>::val,
OFFSET_CHAR<i, 9>::val,*/
NULL_CHAR::val>::type type;
};
template <unsigned int i>
const char IntToStr<i>::str[] =
{
OFFSET_CHAR<i, 0>::val,
OFFSET_CHAR<i, 1>::val,
OFFSET_CHAR<i, 2>::val,
OFFSET_CHAR<i, 3>::val,
OFFSET_CHAR<i, 4>::val,
OFFSET_CHAR<i, 5>::val,
OFFSET_CHAR<i, 6>::val,
OFFSET_CHAR<i, 7>::val,
OFFSET_CHAR<i, 8>::val,
OFFSET_CHAR<i, 9>::val,
NULL_CHAR::val
};
template <bool condition, class Then, class Else>
struct IF
{
typedef Then RET;
};
template <class Then, class Else>
struct IF<false, Then, Else>
{
typedef Else RET;
};
template < typename Str1, typename Str2 >
struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};
template <typename Str1, typename Str2, typename Str3 >
struct concat3 : mpl::insert_range<Str1, typename mpl::end<Str1>::type, typename concat<Str2, Str3 >::type > {};
typedef typename mpl::string<'f','i','z','z'>::type fizz;
typedef typename mpl::string<'b','u','z','z'>::type buzz;
typedef typename mpl::string<'\r', '\n'>::type mpendl;
typedef typename concat<fizz, buzz>::type fizzbuzz;
// discovered boost mpl limitation on some length
template <int N>
struct FizzBuzz
{
typedef typename concat3<typename FizzBuzz<N - 1>::type, typename IF<N % 15 == 0, typename fizzbuzz::type, typename IF<N % 3 == 0, typename fizz::type, typename IF<N % 5 == 0, typename buzz::type, typename IntToStr<N>::type >::RET >::RET >::RET, typename mpendl::type>::type type;
};
template <>
struct FizzBuzz<1>
{
typedef mpl::string<'1','\r','\n'>::type type;
};
int main(int argc, char** argv)
{
const int n = 7;
std::cout << mpl::c_str<FizzBuzz<n>::type>::value << std::endl;
return 0;
}
Note: it takes up lots of memory and takes several seconds to compile. To enable compilation for 7 < n <= 25, please, modify include/boost/mpl/limits/string.hpp BOOST_MPL_LIMIT_STRING_SIZE to 128 instead of 32).
Casio BASIC
See FizzBuzz/Basic
Cduce
(* FizzBuzz in CDuce *)
let format (n : Int) : Latin1 =
if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz"
else if (n mod 5 = 0) then "Buzz"
else if (n mod 3 = 0) then "Fizz"
else string_of (n);;
let fizz (n : Int, size : Int) : _ =
print (format (n) @ "\n");
if (n = size) then
n = 0 (* do nothing *)
else
fizz(n + 1, size);;
let fizbuzz (size : Int) : _ = fizz (1, size);;
let _ = fizbuzz(100);;
Ceylon
shared void run() => {for (i in 1..100) {for (j->k in [3->"Fizz", 5->"Buzz"]) if (j.divides(i)) k}.reduce(plus) else i}.each(print);
Chapel
proc fizzbuzz(n) {
for i in 1..n do
if i % 15 == 0 then
writeln("FizzBuzz");
else if i % 5 == 0 then
writeln("Buzz");
else if i % 3 == 0 then
writeln("Fizz");
else
writeln(i);
}
fizzbuzz(100);
Chef
See FizzBuzz/EsoLang
Clay
main() {
for(i in range(1,100)) {
if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz");
else if(i % 3 == 0) println("fizz");
else if(i % 5 == 0) println("buzz");
else print(i);
}
}
Clipper
Also compiles with Harbour (Harbour 3.2.0dev (r1405201749))
PROCEDURE Main()
LOCAL n
LOCAL cFB
FOR n := 1 TO 100
cFB := ""
AEval( { { 3, "Fizz" }, { 5, "Buzz" } }, {|x| cFB += iif( ( n % x[ 1 ] ) == 0, x[ 2 ], "" ) } )
?? iif( cFB == "", LTrim( Str( n ) ), cFB ) + iif( n == 100, ".", ", " )
NEXT
RETURN
The advantage of this approach is that it is trivial to add another factor:
AEval( {{3,"Fizz"},{5,"Buzz"},{9,"Jazz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")})
CLIPS
(deffacts count
(count-to 100)
)
(defrule print-numbers
(count-to ?max)
=>
(loop-for-count (?num ?max) do
(if
(= (mod ?num 3) 0)
then
(printout t "Fizz")
)
(if
(= (mod ?num 5) 0)
then
(printout t "Buzz")
)
(if
(and (> (mod ?num 3) 0) (> (mod ?num 5) 0))
then
(printout t ?num)
)
(priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf)
)
)
Clojure
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz"))))
(defn fizzbuzz [start finish]
(map (fn [n]
(cond
(zero? (mod n 15)) "FizzBuzz"
(zero? (mod n 3)) "Fizz"
(zero? (mod n 5)) "Buzz"
:else n))
(range start finish)))
(fizzbuzz 1 100)
(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz"
(zero? (mod x 5)) "Buzz"
(zero? (mod x 3)) "Fizz"
:else x))
(range 1 101))
(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101))
(def fizzbuzz (map
#(cond (zero? (mod % 15)) "FizzBuzz"
(zero? (mod % 5)) "Buzz"
(zero? (mod % 3)) "Fizz"
:else %)
(iterate inc 1)))
(defn fizz-buzz
([] (fizz-buzz (range 1 101)))
([lst]
(letfn [(fizz? [n] (zero? (mod n 3)))
(buzz? [n] (zero? (mod n 5)))]
(let [f "Fizz"
b "Buzz"
items (map (fn [n]
(cond (and (fizz? n) (buzz? n)) (str f b)
(fizz? n) f
(buzz? n) b
:else n))
lst)] items))))
(map (fn [n]
(if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz")
(when (zero? (mod n 5)) "Buzz")))]
(apply str fb)
n))
(range 1 101))
(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) )
(range)
(cycle [ "" "" "Fizz" ])
(cycle [ "" "" "" "" "Buzz" ])))
(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % "Fizz" "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101))
(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)]
(take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))
(take 100
(map #(if (pos? (compare %1 %2)) %1 %2)
(map str (drop 1 (range)))
(map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"]))))
;;Using clojure maps
(defn fizzbuzz
[n]
(let [rule {3 "Fizz"
5 "Buzz"}
divs (->> rule
(map first)
sort
(filter (comp (partial = 0)
(partial rem n))))]
(if (empty? divs)
(str n)
(->> divs
(map rule)
(apply str)))))
(defn allfizzbuzz
[max]
(map fizzbuzz (range 1 (inc max))))
(take 100
(map #(str %1 %2 (if-not (or %1 %2) %3))
(cycle [nil nil "Fizz"])
(cycle [nil nil nil nil "Buzz"])
(rest (range))
))
(take 100
(
(fn [& fbspec]
(let [
fbseq #(->> (repeat nil) (cons %2) (take %1) reverse cycle)
strfn #(apply str (if (every? nil? (rest %&)) (first %&)) (rest %&))
]
(->>
fbspec
(partition 2)
(map #(apply fbseq %))
(apply map strfn (rest (range)))
) ;;endthread
) ;;endlet
) ;;endfn
3 "Fizz" 5 "Buzz" 7 "Bazz"
) ;;endfn apply
) ;;endtake
(take 100
(map-indexed
#(case %2 14 "FizzBuzz" (2 5 8 11) "Fizz" (4 9) "Buzz" (inc %1))
(cycle (range 15))
)
)
(take 100
(->>
(map str (cycle [nil nil "Fizz"]) (cycle [nil nil nil nil "Buzz"]))
(map-indexed #(if (empty? %2) (inc %1) %2))
)
)
(take 100
(map-indexed
#(if (number? %2) (+ %1 %2) %2)
(cycle [1 1 "Fizz" 1 "Buzz" "Fizz" 1 1 "Fizz" "Buzz" 1 "Fizz" 1 1 "FizzBuzz"])
)
)
CLU
start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to(1, 100) do
out: string := ""
if i // 3 = 0 then out := out || "Fizz" end
if i // 5 = 0 then out := out || "Buzz" end
if string$empty(out) then out := int$unparse(i) end
stream$putl(po, out)
end
end start_up
CMake
foreach(i RANGE 1 100)
math(EXPR off3 "${i} % 3")
math(EXPR off5 "${i} % 5")
if(NOT off3 AND NOT off5)
message(FizzBuzz)
elseif(NOT off3)
message(Fizz)
elseif(NOT off5)
message(Buzz)
else()
message(${i})
endif()
endforeach(i)
COBOL
Canonical version
* FIZZBUZZ.COB
* cobc -x -g FIZZBUZZ.COB
*
IDENTIFICATION DIVISION.
PROGRAM-ID. fizzbuzz.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CNT PIC 9(03) VALUE 1.
01 REM PIC 9(03) VALUE 0.
01 QUOTIENT PIC 9(03) VALUE 0.
PROCEDURE DIVISION.
*
PERFORM UNTIL CNT > 100
DIVIDE 15 INTO CNT GIVING QUOTIENT REMAINDER REM
IF REM = 0
THEN
DISPLAY "FizzBuzz " WITH NO ADVANCING
ELSE
DIVIDE 3 INTO CNT GIVING QUOTIENT REMAINDER REM
IF REM = 0
THEN
DISPLAY "Fizz " WITH NO ADVANCING
ELSE
DIVIDE 5 INTO CNT GIVING QUOTIENT REMAINDER REM
IF REM = 0
THEN
DISPLAY "Buzz " WITH NO ADVANCING
ELSE
DISPLAY CNT " " WITH NO ADVANCING
END-IF
END-IF
END-IF
ADD 1 TO CNT
END-PERFORM
DISPLAY ""
STOP RUN.
Simpler version
I know this doesn't have the full-bodied, piquant flavor expected from COBOL, but it is a little shorter.
Identification division.
Program-id. fizz-buzz.
Data division.
Working-storage section.
01 num pic 999.
Procedure division.
Perform varying num from 1 by 1 until num > 100
if function mod (num, 15) = 0 then display "fizzbuzz"
else if function mod (num, 3) = 0 then display "fizz"
else if function mod (num, 5) = 0 then display "buzz"
else display num
end-perform.
Stop run.
Evaluate Version
I think this shows clearly that it's resolving the problem and illuminating the rules specified
IDENTIFICATION DIVISION.
PROGRAM-ID. FIZZBUZZ.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 X PIC 999.
01 Y PIC 999.
01 REM3 PIC 999.
01 REM5 PIC 999.
PROCEDURE DIVISION.
PERFORM VARYING X FROM 1 BY 1 UNTIL X > 100
DIVIDE X BY 3 GIVING Y REMAINDER REM3
DIVIDE X BY 5 GIVING Y REMAINDER REM5
EVALUATE REM3 ALSO REM5
WHEN ZERO ALSO ZERO
DISPLAY "FizzBuzz"
WHEN ZERO ALSO ANY
DISPLAY "Fizz"
WHEN ANY ALSO ZERO
DISPLAY "Buzz"
WHEN OTHER
DISPLAY X
END-EVALUATE
END-PERFORM
STOP RUN
.
Chase the Fizz
A solution that simply evaluates and adds.
>>SOURCE FORMAT FREE
identification division.
program-id. fizzbuzz.
data division.
working-storage section.
01 i pic 999.
01 fizz pic 999 value 3.
01 buzz pic 999 value 5.
procedure division.
start-fizzbuzz.
perform varying i from 1 by 1 until i > 100
evaluate i also i
when fizz also buzz
display 'fizzbuzz'
add 3 to fizz
add 5 to buzz
when fizz also any
display 'fizz'
add 3 to fizz
when buzz also any
display 'buzz'
add 5 to buzz
when other
display i
end-evaluate
end-perform
stop run
.
end program fizzbuzz.
Coco
for i from 1 to 100
console.log do
if i % 15 == 0 then 'FizzBuzz'
else if i % 3 == 0 then 'Fizz'
else if i % 5 == 0 then 'Buzz'
else i
for i from 1 to 100
console.log(['Fizz' unless i % 3] + ['Buzz' unless i % 5] or String(i))
Coconut
def fizzbuzz(n):
case (n % 3, n % 5):
match (0, 0): return "FizzBuzz"
match (0, _): return "Fizz"
match (_, 0): return "Buzz"
else: return n |> str
range(1,101)|> map$(fizzbuzz)|> x -> '\n'.join(x)|> print
CoffeeScript
for i in [1..100]
if i % 15 is 0
console.log "FizzBuzz"
else if i % 3 is 0
console.log "Fizz"
else if i % 5 is 0
console.log "Buzz"
else
console.log i
for i in [1..100]
console.log \
if i % 15 is 0
"FizzBuzz"
else if i % 3 is 0
"Fizz"
else if i % 5 is 0
"Buzz"
else
i
for i in [1..100]
console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)
ColdFusion
<Cfloop from="1" to="100" index="i">
<Cfif i mod 15 eq 0>FizzBuzz
<Cfelseif i mod 5 eq 0>Fizz
<Cfelseif i mod 3 eq 0>Buzz
<Cfelse><Cfoutput>#i# </Cfoutput>
</Cfif>
</Cfloop>
cfscript version
<cfscript>
result = "";
for(i=1;i<=100;i++){
result=ListAppend(result, (i%15==0) ? "FizzBuzz": (i%5==0) ? "Buzz" : (i%3 eq 0)? "Fizz" : i );
}
WriteOutput(result);
</cfscript>
Comal
0010 FOR i#:=1 TO 100 DO
0020 IF i# MOD 15=0 THEN
0030 PRINT "FizzBuzz"
0040 ELIF i# MOD 5=0 THEN
0050 PRINT "Buzz"
0060 ELIF i# MOD 3=0 THEN
0070 PRINT "Fizz"
0080 ELSE
0090 PRINT i#
0100 ENDIF
0110 ENDFOR i#
0120 END
Comefrom0x10
fizzbuzz
mod_three = 3
mod_five = 5
comefrom fizzbuzz
n
comefrom fizzbuzz if n is mod_three
comefrom fizzbuzz if n is mod_five
n = n + 1
fizz
comefrom fizzbuzz if n is mod_three
'Fizz'...
mod_three = mod_three + 3
linebreak
# would like to write "unless mod_three is mod_five"
comefrom fizz if mod_three - mod_five - 3
''
buzz
comefrom fizzbuzz if n is mod_five
'Buzz'
mod_five = mod_five + 5
comefrom fizzbuzz if n is 100
Common Lisp
Solution 1:
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(princ (cond ((zerop (mod x 15)) "FizzBuzz")
((zerop (mod x 3)) "Fizz")
((zerop (mod x 5)) "Buzz")
(t x)))
(terpri)))
Solution 2:
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(format t "~&~{~A~}"
(or (append (when (zerop (mod x 3)) '("Fizz"))
(when (zerop (mod x 5)) '("Buzz")))
(list x)))))
Solution 3:
(defun fizzbuzz ()
(loop for n from 1 to 100
do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%"
(mod n 3) (mod n 5) n)))
Solution 4:
(loop as n from 1 to 100
as fizz = (zerop (mod n 3))
as buzz = (zerop (mod n 5))
as numb = (not (or fizz buzz))
do
(format t
"~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%"
fizz buzz numb n))
Solution 5:
(format t "~{~:[~&~;~:*~:(~a~)~]~}"
(loop as n from 1 to 100
as f = (zerop (mod n 3))
as b = (zerop (mod n 5))
collect nil
if f collect 'fizz
if b collect 'buzz
if (not (or f b)) collect n))
Solution 6:
(format t "~{~{~:[~;Fizz~]~:[~;Buzz~]~:[~*~;~d~]~}~%~}"
(loop as n from 1 to 100
as f = (zerop (mod n 3))
as b = (zerop (mod n 5))
collect (list f b (not (or f b)) n)))
Solution 7:
(defun core (x)
(mapcar
#'(lambda (a b) (if (equal 0 (mod x a)) b x))
'(3 5)
'("fizz" "buzz")))
(defun filter-core (x)
(if (equal 1 (length (remove-duplicates x)))
(list (car x))
(remove-if-not #'stringp x)))
(defun fizzbuzz (x)
(loop for a from 1 to x do
(print (format nil "~{~a~}" (filter-core (core a))))))
(fizzbuzz 100)
First 16 lines of output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16
Alternate solution
I use Allegro CL 10.1
;; Project : FizzBuzz
(defun fizzbuzz (&optional n)
(let ((n (or n 1)))
(if (> n 100)
nil
(progn
(let ((mult-3 (is-mult-p n 3))
(mult-5 (is-mult-p n 5)))
(if mult-3
(princ "Fizz"))
(if mult-5
(princ "Buzz"))
(if (not (or mult-3 mult-5))
(princ n))
(princ #\linefeed)
(fizzbuzz (+ n 1)))))))
(defun is-mult-p (n multiple)
(= (rem n multiple) 0))
(fizzbuzz 1)
Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
Coq
Require Import Coq.Lists.List.
(* https://coq.inria.fr/library/Coq.Lists.List.html *)
Require Import Coq.Strings.String.
(* https://coq.inria.fr/library/Coq.Strings.String.html *)
Require Import Coq.Strings.Ascii.
(* https://coq.inria.fr/library/Coq.Strings.Ascii.html *)
Require Import Coq.Init.Nat.
(* https://coq.inria.fr/library/Coq.Init.Nat.html *)
(** Definition of [string_of_nat] to convert natural numbers to strings. *)
Definition ascii_of_digit (n: nat): ascii :=
ascii_of_nat (n + 48).
Definition is_digit (n: nat): bool :=
andb (0 <=? n) (n <=? 9).
Fixpoint rec_string_of_nat (counter: nat) (n: nat) (acc: string): string :=
match counter with
| 0 => EmptyString
| S c =>
if (is_digit n)
then String (ascii_of_digit n) acc
else rec_string_of_nat c (n / 10) (String (ascii_of_digit (n mod 10)) acc)
end.
(** The counter is only used to ensure termination. *)
Definition string_of_nat (n: nat): string :=
rec_string_of_nat n n EmptyString.
(** The FizzBuzz problem. *)
Definition fizz: string :=
"Fizz" .
Definition buzz: string :=
"Buzz" .
Definition new_line: string :=
String (ascii_of_nat 10) EmptyString.
Definition is_divisible_by (n: nat) (k: nat): bool :=
(n mod k) =? 0.
Definition get_fizz_buzz_term (n: nat): string :=
if (is_divisible_by n 15) then fizz ++ buzz
else if (is_divisible_by n 3) then fizz
else if (is_divisible_by n 5) then buzz
else (string_of_nat n).
Definition get_first_positive_numbers (n: nat): list nat :=
seq 1 n.
Definition fizz_buzz_terms (n: nat): list string :=
map get_fizz_buzz_term (get_first_positive_numbers n).
Definition fizz_buzz: string :=
concat new_line (fizz_buzz_terms 100).
(** This shows the string. *)
Eval compute in fizz_buzz.
Cowgol
Straightforward version
include "cowgol.coh";
var i: uint8 := 1;
while i <= 100 loop
if i % 15 == 0 then
print("FizzBuzz");
elseif i % 5 == 0 then
print("Buzz");
elseif i % 3 == 0 then
print("Fizz");
else
print_i8(i);
end if;
print_nl();
i := i + 1;
end loop;
No division
When targeting small systems, it is generally a good idea not to use division if you don't have to. Most of the processors Cowgol targets do not have hardware division, requiring the use of slow and bulky software division routines. This is not helped by the fact that these processors are not fast to begin with, and memory is usually scarce.
Avoiding division requires not only that %
be avoided, but also
print_i8
cannot be used, as printing integers in decimal format
is also done by division. Instead, this code keeps separate 'fizz' and 'buzz'
counters around, as well as keeping the number ready in ASCII format for printing.
Nevertheless, the following code compiles to a
252-byte 8080 executable, whereas the naive version above compiles to a 755-byte
executable. (Compare to the 8080 assembly program above, which assembles to a
98-byte executable.)
include "cowgol.coh";
var i: uint8 := 100;
var fizz: uint8 := 3;
var buzz: uint8 := 5;
var dh: uint8 := '0';
var dl: uint8 := '1';
var prnum: uint8;
while i != 0 loop
fizz := fizz - 1;
buzz := buzz - 1;
prnum := 1;
if fizz == 0 then
print("Fizz");
fizz := 3;
prnum := 0;
end if;
if buzz == 0 then
print("Buzz");
buzz := 5;
prnum := 0;
end if;
if prnum != 0 then
if dh != '0' then
print_char(dh);
end if;
print_char(dl);
end if;
dl := dl + 1;
if dl == ('9' + 1) then
dl := '0';
dh := dh + 1;
end if;
print_nl();
i := i - 1;
end loop;
Crystal
1.upto(100) do |v|
p fizz_buzz(v)
end
def fizz_buzz(value)
word = ""
word += "fizz" if value % 3 == 0
word += "buzz" if value % 5 == 0
word += value.to_s if word.empty?
word
end
A more natural solution with the string building:
1.upto(100) do |n|
case
when n % 15 == 0
puts "FizzBuzz"
when n % 5 == 0
puts "Buzz"
when n % 3 == 0
puts "Fizz"
else
puts n
end
end
CSS
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <style> li { list-style-position: inside; } li:nth-child(3n), li:nth-child(5n) { list-style-type: none; } li:nth-child(3n)::before { content:'Fizz'; } li:nth-child(5n)::after { content:'Buzz'; } </style> </head> <body> <ol> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ol> </body> </html>
Cubescript
alias fizzbuzz [
loop i 100 [
push i (+ $i 1) [
cond (! (mod $i 15)) [
echo FizzBuzz
] (! (mod $i 3)) [
echo Fizz
] (! (mod $i 5)) [
echo Buzz
] [
echo $i
]
]
]
]
D
import std.stdio, std.algorithm, std.conv;
/// With if-else.
void fizzBuzz(in uint n) {
foreach (immutable i; 1 .. n + 1)
if (!(i % 15))
"FizzBuzz".writeln;
else if (!(i % 3))
"Fizz".writeln;
else if (!(i % 5))
"Buzz".writeln;
else
i.writeln;
}
/// With switch case.
void fizzBuzzSwitch(in uint n) {
foreach (immutable i; 1 .. n + 1)
switch (i % 15) {
case 0:
"FizzBuzz".writeln;
break;
case 3, 6, 9, 12:
"Fizz".writeln;
break;
case 5, 10:
"Buzz".writeln;
break;
default:
i.writeln;
}
}
void fizzBuzzSwitch2(in uint n) {
foreach (immutable i; 1 .. n + 1)
(i % 15).predSwitch(
0, "FizzBuzz",
3, "Fizz",
5, "Buzz",
6, "Fizz",
9, "Fizz",
10, "Buzz",
12, "Fizz",
/*else*/ i.text).writeln;
}
void main() {
100.fizzBuzz;
writeln;
100.fizzBuzzSwitch;
writeln;
100.fizzBuzzSwitch2;
}
Alternate version calculating values at compile time:
import std;
void main()
{
auto fizzbuzz(in uint i)
{
string r;
if (i % 3 == 0) r ~= "fizz";
if (i % 5 == 0) r ~= "buzz";
if (r.length == 0) r ~= i.to!string;
return r;
}
enum r = 1.iota(101).map!fizzbuzz;
r.each!writeln;
}
Dart
main() {
for (int i = 1; i <= 100; i++) {
List<String> out = [];
if (i % 3 == 0)
out.add("Fizz");
if (i % 5 == 0)
out.add("Buzz");
print(out.length > 0 ? out.join("") : i);
}
}
dc
[[Fizz]P 1 sw]sF
[[Buzz]P 1 sw]sB
[li p sz]sN
[[
]P]sW
[
0 sw [w = 0]sz
li 3 % 0 =F [Fizz if 0 == i % 3]sz
li 5 % 0 =B [Buzz if 0 == i % 5]sz
lw 0 =N [print Number if 0 == w]sz
lw 1 =W [print neWline if 1 == w]sz
li 1 + si [i += 1]sz
li 100 !<L [continue Loop if 100 >= i]sz
]sL
1 si [i = 1]sz
0 0 =L [enter Loop]sz
The bc translation written in dc style.
# dc is stack based, so we use the stack instead of a variable for our
# current number.
1 # Number = 1
[[Fizz]n 1 sw]sF # Prints "Fizz" prevents Number from printing
[[Buzz]n 1 sw]sB # Prints "Buzz" prevents Number from printing
[dn]sN # Prints Number
[
dd # Put two extra copies of Number on stack
0 sw # w = 0
3% 0=F # Fizz if 0 == Number % 3 (destroys 1st copy)
5% 0=B # Buzz if 0 == Number % 5 (destroys 2nd copy)
lw 0=N # Print Number if 0 == w
[
]n # Print new line
1+d # Number += 1 and put extra copy on stack
100!<L # Continue Loop if 100 >= Number (destroys copy)
]dsLx # Enter Loop
Delphi
program FizzBuzz;
{$APPTYPE CONSOLE}
uses SysUtils;
var
i: Integer;
begin
for i := 1 to 100 do
begin
if i mod 15 = 0 then
Writeln('FizzBuzz')
else if i mod 3 = 0 then
Writeln('Fizz')
else if i mod 5 = 0 then
Writeln('Buzz')
else
Writeln(i);
end;
end.
DeviousYarn
each { x range(1 100)
? { divisible(x 3)
p:'Fizz' }
? { divisible(x 5)
p:'Buzz' }
-? { !:divisible(x 3)
p:x }
o
}
Draco
proc nonrec main() void:
byte i;
for i from 1 upto 100 do
if i % 15 = 0 then writeln("FizzBuzz")
elif i % 5 = 0 then writeln("Buzz")
elif i % 3 = 0 then writeln("Fizz")
else writeln(i)
fi
od
corp
DUP
FizzBuzz, realized using two different methods for string/character output:
Output to STDOUT via single character output.
[$$3/%$[]['F,'i,'z,'z,]?\5/%$[]['B,'u,'z,'z,]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print proper output}
0[$100<][1+c;!]# {loop from 1 to 100}
Output to STDOUT, using stored strings and a separately defined string output operator:
[\[^^>][$;,1+]#%%]⇒P {define operator P: print stored string}
[$$3/%$[][0$"Fizz"P]?\5/%$[][0$"Buzz"P]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print according output}
0[$100<][1+c;!]# {loop from 1 to 100}
DWScript
var i : Integer;
for i := 1 to 100 do begin
if i mod 15 = 0 then
PrintLn('FizzBuzz')
else if i mod 3 = 0 then
PrintLn('Fizz')
else if i mod 5 = 0 then
PrintLn('Buzz')
else PrintLn(i);
end;
Dyalect
var n = 1
while n < 20 {
if n % 15 == 0 {
print("fizzbuzz")
} else if n % 3 == 0 {
print("fizz")
} else if n % 5 == 0 {
print("buzz")
} else {
print(n)
}
n = n + 1
}
- Output:
1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19
Déjà Vu
for i range 1 100:
if = 0 % i 15:
"FizzBuzz"
elseif = 0 % i 3:
"Fizz"
elseif = 0 % i 5:
"Buzz"
else:
i
!print
E
for i in 1..100 {
println(switch ([i % 3, i % 5]) {
match [==0, ==0] { "FizzBuzz" }
match [==0, _ ] { "Fizz" }
match [_, ==0] { "Buzz" }
match _ { i }
})
}
EasyLang
for i = 1 to 100
if i mod 15 = 0
print "FizzBuzz"
elif i mod 5 = 0
print "Buzz"
elif i mod 3 = 0
print "Fizz"
else
print i
.
.
ECL
DataRec := RECORD
STRING s;
END;
DataRec MakeDataRec(UNSIGNED c) := TRANSFORM
SELF.s := MAP
(
c % 15 = 0 => 'FizzBuzz',
c % 3 = 0 => 'Fizz',
c % 5 = 0 => 'Buzz',
(STRING)c
);
END;
d := DATASET(100,MakeDataRec(COUNTER));
OUTPUT(d);
Eero
#import <Foundation/Foundation.h>
int main()
autoreleasepool
for int i in 1 .. 100
s := ''
if i % 3 == 0
s << 'Fizz'
if i % 5 == 0
s << 'Buzz'
Log( '(%d) %@', i, s )
return 0
Egel
import "prelude.eg"
import "io.ego"
using System
using IO
def fizzbuzz =
[ 100 -> print "100\n"
| N ->
if and ((N%3) == 0) ((N%5) == 0) then
let _ = print "fizz buzz, " in fizzbuzz (N+1)
else if (N%3) == 0 then
let _ = print "fizz, " in fizzbuzz (N+1)
else if (N%5) == 0 then
let _ = print "buzz, " in fizzbuzz (N+1)
else
let _ = print N ", " in fizzbuzz (N+1) ]
def main = fizzbuzz 1
Eiffel
class
APPLICATION
create
make
feature
make
do
fizzbuzz
end
fizzbuzz
--Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5.
--For multiples of both 3 and 5 prints "FizzBuzz".
do
across
1 |..| 100 as c
loop
if c.item \\ 15 = 0 then
io.put_string ("FIZZBUZZ%N")
elseif c.item \\ 3 = 0 then
io.put_string ("FIZZ%N")
elseif c.item \\ 5 = 0 then
io.put_string ("BUZZ%N")
else
io.put_string (c.item.out + "%N")
end
end
end
end
Ela
open list
prt x | x % 15 == 0 = "FizzBuzz"
| x % 3 == 0 = "Fizz"
| x % 5 == 0 = "Buzz"
| else = x
[1..100] |> map prt
Elixir
Standard approaches
used case
Enum.each 1..100, fn x ->
IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do
{ true, true } -> "FizzBuzz"
{ true, false } -> "Fizz"
{ false, true } -> "Buzz"
{ false, false } -> x
end)
end
Alternate approach using pipes and cond:
#!/usr/bin/env elixir
1..100 |> Enum.map(fn i ->
cond do
rem(i,3*5) == 0 -> "FizzBuzz"
rem(i,3) == 0 -> "Fizz"
rem(i,5) == 0 -> "Buzz"
true -> i
end
end) |> Enum.each(fn i -> IO.puts i end)
used Stream.cycle version:
defmodule RC do
def fizzbuzz(limit \\ 100) do
fizz = Stream.cycle(["", "", "Fizz"])
buzz = Stream.cycle(["", "", "", "", "Buzz"])
Stream.zip(fizz, buzz)
|> Enum.take(limit)
|> Enum.with_index
|> Enum.each(fn {{f,b},i} ->
IO.puts if f<>b=="", do: i+1, else: f<>b
end)
end
end
RC.fizzbuzz
Yet another approach:
defmodule FizzBuzz do
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz"
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
def fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz"
def fizzbuzz(n), do: n
end
Enum.each(1..100, &IO.puts FizzBuzz.fizzbuzz &1)
used anonymous function
f = fn(n) when rem(n,15)==0 -> "FizzBuzz"
(n) when rem(n,5)==0 -> "Fizz"
(n) when rem(n,3)==0 -> "Buzz"
(n) -> n
end
for n <- 1..100, do: IO.puts f.(n)
Enum.at version: Returns nil if index is out of bounds.
Enum.each(1..100, fn i ->
str = "#{Enum.at([:Fizz], rem(i,3))}#{Enum.at([:Buzz], rem(i,5))}"
IO.puts if str=="", do: i, else: str
end)
A macro too far
The Stream.cycle version above, but as an overpowered FizzBuzz DSL.
defmodule BadFizz do
# Hand-rolls a bunch of AST before injecting the resulting FizzBuzz code.
defmacrop automate_fizz(fizzers, n) do
# To begin, we need to process fizzers to produce the various components
# we're using in the final assembly. As told by Mickens telling as Antonio
# Banderas, first you must specify a mapping function:
build_parts = (fn {fz, n} ->
ast_ref = {fz |> String.downcase |> String.to_atom, [], __MODULE__}
clist = List.duplicate("", n - 1) ++ [fz]
cycle = quote do: unquote(ast_ref) = unquote(clist) |> Stream.cycle
{ast_ref, cycle}
end)
# ...and then a reducing function:
collate = (fn
({ast_ref, cycle}, {ast_refs, cycles}) ->
{[ast_ref | ast_refs], [cycle | cycles]}
end)
# ...and then, my love, when you are done your computation is ready to run
# across thousands of fizzbuzz:
{ast_refs, cycles} = fizzers
|> Code.eval_quoted([], __ENV__) |> elem(0) # Gotta unwrap this mystery code~
|> Enum.sort(fn ({_, ap}, {_, bp}) -> ap < bp end) # Sort so that Fizz, 3 < Buzz, 5
|> Enum.map(build_parts)
|> Enum.reduce({[], []}, collate)
# Setup the anonymous functions used by Enum.reduce to build our AST components.
# This was previously handled by List.foldl, but ejected because reduce/2's
# default behavior reduces repetition.
#
# ...I was tempted to move these into a macro themselves, and thought better of it.
build_zip = fn (varname, ast) ->
quote do: Stream.zip(unquote(varname), unquote(ast))
end
build_tuple = fn (varname, ast) ->
{:{}, [], [varname, ast]}
end
build_concat = fn (varname, ast) ->
{:<>,
[context: __MODULE__, import: Kernel], # Hygiene values may change; accurate to Elixir 1.1.1
[varname, ast]}
end
# Toss cycles into a block by hand, then smash ast_refs into
# a few different computations on the cycle block results.
cycles = {:__block__, [], cycles}
tuple = ast_refs |> Enum.reduce(build_tuple)
zip = ast_refs |> Enum.reduce(build_zip)
concat = ast_refs |> Enum.reduce(build_concat)
# Finally-- Now that all our components are assembled, we can put
# together the fizzbuzz stream pipeline. After quote ends, this
# block is injected into the caller's context.
quote do
unquote(cycles)
unquote(zip)
|> Stream.with_index
|> Enum.take(unquote(n))
|> Enum.each(fn
{unquote(tuple), i} ->
ccats = unquote(concat)
IO.puts if ccats == "", do: i + 1, else: ccats
end)
end
end
@doc ~S"""
A fizzing, and possibly buzzing function. Somehow, you feel like you've
seen this before. An old friend, suddenly appearing in Kafkaesque nightmare...
...or worse, during a whiteboard interview.
"""
def fizz(n \\ 100) when is_number(n) do
# In reward for all that effort above, we now have the latest in
# programmer productivity:
#
# A DSL for building arbitrary fizzing, buzzing, bazzing, and more!
[{"Fizz", 3},
{"Buzz", 5}#,
#{"Bar", 7},
#{"Foo", 243}, # -> Always printed last (largest number)
#{"Qux", 34}
]
|> automate_fizz(n)
end
end
BadFizz.fizz(100) # => Prints to stdout
Elm
A bit too simple:
import Html exposing (text)
import List exposing (map)
main =
[1..100] |> map getWordForNum |> text
getWordForNum num =
if num % 15 == 0 then
"FizzBuzz"
else if num % 3 == 0 then
"Fizz"
else if num % 5 == 0 then
"Buzz"
else
String.fromInt num
A bit too clever:
import Html exposing (text)
import List exposing (map)
import String exposing (join, fromInt)
main : Html.Html
main =
[1..100] |> map fizzbuzz |> join " " |> text
fizzbuzz : Int -> String
fizzbuzz num =
let
fizz = if num % 3 == 0 then "Fizz" else ""
buzz = if num % 5 == 0 then "Buzz" else ""
in
if fizz == buzz then
fromInt num
else
fizz ++ buzz
Emacs Lisp
(defun fizzbuzz (n)
(cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz")
((zerop (% n 3)) "Fizz")
((zerop (% n 5)) "Buzz")
(t n)))
;; loop & print from 0 to 100
(dotimes (i 101)
(message "%s" (fizzbuzz i)))
Emojicode
Simple 1
🏁🍇
🔂 i 🆕⏩ 1 101 1 ❗ 🍇
↪️ i 🚮 15 🙌 0 🍇
😀 🔤FizzBuzz🔤 ❗
🍉
🙅↪️ i 🚮 3 🙌 0 🍇
😀 🔤Fizz🔤 ❗
🍉
🙅↪️ i 🚮 5 🙌 0 🍇
😀 🔤Buzz🔤 ❗
🍉🙅🍇
😀 🔤🧲i🧲🔤 ❗
🍉
🍉
🍉
Simple 2
🏁🍇
🔂 i 🆕⏩ 1 101 1 ❗ 🍇
🔤🔤 ➡️ 🖍🆕 msg
↪️ i 🚮 3 🙌 0 🍇
🔤Fizz🔤 ➡️ 🖍 msg
🍉
↪️ i 🚮 5 🙌 0 🍇
🔤🧲msg🧲Buzz🔤 ➡️ 🖍 msg
🍉
↪️ msg 🙌 🔤🔤 🍇
😀 🔤🧲i🧲🔤 ❗
🍉🙅🍇
😀 🔤🧲msg🧲🔤 ❗
🍉
🍉
🍉
Erlang
-spec fizzbuzz() -> Result :: string().
fizzbuzz() ->
F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
(N) when N rem 3 == 0 -> "Fizz";
(N) when N rem 5 == 0 -> "Buzz";
(N) -> integer_to_list(N)
end,
lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).
ERRE
PROGRAM FIZZ_BUZZ
!
! for rosettacode.org
!
BEGIN
FOR A=1 TO 100 DO
IF A MOD 15=0 THEN
PRINT("FizzBuzz")
ELSIF A MOD 3=0 THEN
PRINT("Fizz")
ELSIF A MOD 5=0 THEN
PRINT("Buzz")
ELSE
PRINT(A)
END IF
END FOR
END PROGRAM
Euphoria
This is based on the VBScript example.
include std/utils.e
function fb( atom n )
sequence fb
if remainder( n, 15 ) = 0 then
fb = "FizzBuzz"
elsif remainder( n, 5 ) = 0 then
fb = "Fizz"
elsif remainder( n, 3 ) = 0 then
fb = "Buzz"
else
fb = sprintf( "%d", n )
end if
return fb
end function
function fb2( atom n )
return iif( remainder(n, 15) = 0, "FizzBuzz",
iif( remainder( n, 5 ) = 0, "Fizz",
iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) )
end function
for i = 1 to 30 do
printf( 1, "%s ", { fb( i ) } )
end for
puts( 1, "\n" )
for i = 1 to 30 do
printf( 1, "%s ", { fb2( i ) } )
end for
puts( 1, "\n" )
F#
let fizzbuzz n =
match n%3 = 0, n%5 = 0 with
| true, false -> "fizz"
| false, true -> "buzz"
| true, true -> "fizzbuzz"
| _ -> string n
let printFizzbuzz() =
[1..100] |> List.iter (fizzbuzz >> printfn "%s")
[1..100]
|> List.map (fun x ->
match x with
| _ when x % 15 = 0 ->"fizzbuzz"
| _ when x % 5 = 0 -> "buzz"
| _ when x % 3 = 0 -> "fizz"
| _ -> x.ToString())
|> List.iter (fun x -> printfn "%s" x)
Another example using (unnecessary) partial active pattern :D
let (|MultipleOf|_|) divisors number =
if Seq.exists ((%) number >> (<>) 0) divisors
then None
else Some ()
let fizzbuzz = function
| MultipleOf [3; 5] -> "fizzbuzz"
| MultipleOf [3] -> "fizz"
| MultipleOf [5] -> "buzz"
| n -> string n
{ 1 .. 100 }
|> Seq.iter (fizzbuzz >> printfn "%s")
Factor
USING: math kernel io math.functions math.parser math.ranges ;
IN: fizzbuzz
: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ;
: buzz ( n -- str ) 5 divisor? "Buzz" "" ? ;
: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;
: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;
MAIN: main
More flexible variant without divisibility tests.
USING: kernel sequences arrays generalizations fry math math.parser prettyprint ;
IN: fizzbuzz
: zz ( m seq -- v ) dup length 1 <array> V{ } clone 4 -nrot 1 4 -nrot 3 nrot
'[ dup _ <= ]
3 -nrot
'[
"" _ [ _ [ swap execute( str n -- str n ) ] change-nth ] each-index
dup empty? [ drop dup number>string ] [ ] if swapd suffix! swap 1 +
]
while drop ;
: fizz ( str n -- str n ) dup 3 < [ 1 + ] [ drop "Fizz" append 1 ] if ;
: buzz ( str n -- str n ) dup 5 < [ 1 + ] [ drop "Buzz" append 1 ] if ;
: quxx ( str n -- str n ) dup 7 < [ 1 + ] [ drop "Quxx" append 1 ] if ;
: FizzBuzzQuxx ( m -- v ) { fizz buzz quxx } zz ;
: FizzBuzzQuxx-100 ( -- ) 100 FizzBuzzQuxx . ;
MAIN: FizzBuzzQuxx-100
Falcon
for i in [1:101]
switch i % 15
case 0 : > "FizzBuzz"
case 5,10 : > "Buzz"
case 3,6,9,12 : > "Fizz"
default : > i
end
end
FALSE
See FizzBuzz/EsoLang
Fantom
class FizzBuzz
{
public static Void main ()
{
for (Int i:=1; i <= 100; ++i)
{
if (i % 15 == 0)
echo ("FizzBuzz")
else if (i % 3 == 0)
echo ("Fizz")
else if (i % 5 == 0)
echo ("Buzz")
else
echo (i)
}
}
}
FBSL
No 'MOD 15' needed.
#APPTYPE CONSOLE
DIM numbers AS STRING
DIM imod5 AS INTEGER
DIM imod3 AS INTEGER
FOR DIM i = 1 TO 100
numbers = ""
imod3 = i MOD 3
imod5 = i MOD 5
IF NOT imod3 THEN numbers = "Fizz"
IF NOT imod5 THEN numbers = numbers & "Buzz"
IF imod3 AND imod5 THEN numbers = i
PRINT numbers, " ";
NEXT
PAUSE
- Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fiz z 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 Fi zzBuzz 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 Press any key to continue...
Fennel
(for [i 1 100]
(print (if (= (% i 15) 0) :FizzBuzz
(= (% i 3) 0) :Fizz
(= (% i 5) 0) :Buzz
i)))
Use pattern matching and recursive function:
(fn fizz-buzz [from to]
(print (match [(% from 3) (% from 5)]
[0 0] :FizzBuzz
[0 _] :Fizz
[_ 0] :Buzz
_ from))
(when (< from to)
(fizz-buzz (+ from 1) to)))
(fizz-buzz 1 100)
Alternative matching pattern:
(for [i 1 100]
(print (match (% i 15)
0 :FizzBuzz
(where (or 3 6 9 12)) :Fizz
(where (or 5 10) :Buzz
_ i)))
FOCAL
FITR is a built-in function that truncates a floating-point number to an integer. Note that FOCAL uses an arithmetic (three-way) IF statement, rather like early Fortran.
01.10 FOR I=1,100; DO 2.0
01.20 QUIT
02.10 SET ZB=I/15 - FITR(I/15)
02.20 IF (ZB) 2.4, 2.3, 2.4
02.30 TYPE "FizzBuzz" !
02.35 RETURN
02.40 SET Z=I/3 - FITR(I/3)
02.50 IF (Z) 2.7, 2.6, 2.7
02.60 TYPE "Fizz" !
02.65 RETURN
02.70 SET B=I/5 - FITR(I/5)
02.80 IF (B) 2.99, 2.9, 2.99
02.90 TYPE "Buzz" !
02.95 RETURN
02.99 TYPE %3, I, !
Fermat
for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od
- Output:
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
Forth
table-driven
: fizz ( n -- ) drop ." Fizz" ;
: buzz ( n -- ) drop ." Buzz" ;
: fb ( n -- ) drop ." FizzBuzz" ;
: vector create does> ( n -- )
over 15 mod cells + @ execute ;
vector .fizzbuzz
' fb , ' . , ' . ,
' fizz , ' . , ' buzz ,
' fizz , ' . , ' . ,
' fizz , ' buzz , ' . ,
' fizz , ' . , ' . ,
or the classic approach
: .fizzbuzz ( n -- )
0 pad c!
dup 3 mod 0= if s" Fizz" pad place then
dup 5 mod 0= if s" Buzz" pad +place then
pad c@ if drop pad count type else . then ;
: zz ( n -- )
1+ 1 do i .fizzbuzz cr loop ;
100 zz
the well factored approach
SYNONYM is a Forth200x word.
SYNONYM NOT INVERT \ Bitwise boolean not
: Fizz? ( n -- ? ) 3 MOD 0= DUP IF ." Fizz" THEN ;
: Buzz? ( n -- ? ) 5 MOD 0= DUP IF ." Buzz" THEN ;
: ?print ( n ? -- ) IF . THEN ;
: FizzBuzz ( -- )
101 1 DO CR I DUP Fizz? OVER Buzz? OR NOT ?print LOOP ;
FizzBuzz
the unrolled approach
: n ( n -- n+1 ) dup . 1+ ;
: f ( n -- n+1 ) ." Fizz " 1+ ;
: b ( n -- n+1 ) ." Buzz " 1+ ;
: fb ( n -- n+1 ) ." FizzBuzz " 1+ ;
: fb10 ( n -- n+10 ) n n f n b f n n f b ;
: fb15 ( n -- n+15 ) fb10 n f n n fb ;
: fb100 ( n -- n+100 ) fb15 fb15 fb15 fb15 fb15 fb15 fb10 ;
: .fizzbuzz ( -- ) 1 fb100 drop ;
Fortran
In ANSI FORTRAN 77 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features):
program fizzbuzz_if
integer :: i
do i = 1, 100
if (mod(i,15) == 0) then; print *, 'FizzBuzz'
else if (mod(i,3) == 0) then; print *, 'Fizz'
else if (mod(i,5) == 0) then; print *, 'Buzz'
else; print *, i
end if
end do
end program fizzbuzz_if
This example uses If statements to print "Fizz" and "Buzz" next to each other if the number is divisible by 3 and 5 by waiting to use a line break until after the If statements.
program FizzBuzz
implicit none
integer :: i = 1
do i = 1, 100
if (Mod(i,3) == 0)write(*,"(A)",advance='no') "Fizz"
if (Mod(i,5) == 0)write(*,"(A)",advance='no') "Buzz"
if (Mod(i,3) /= 0 .and. Mod(i,5) /=0 )write(*,"(I3)",advance='no') i
print *, ""
end do
end program FizzBuzz
In ISO Fortran 90 or later use SELECT-CASE statement:
program fizzbuzz_select
integer :: i
do i = 1, 100
select case (mod(i,15))
case 0; print *, 'FizzBuzz'
case 3,6,9,12; print *, 'Fizz'
case 5,10; print *, 'Buzz'
case default; print *, i
end select
end do
end program fizzbuzz_select
FreeBASIC
See FizzBuzz/Basic
Frege
gen n word = cycle (take (n - 1) (repeat "") ++ [word])
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")
fizzbuzz = zipWith combine pattern [1..] where
combine word number = if null word
then show number
else word
show $ take 100 fizzbuzz
Frink
for i = 1 to 100
{
flag = false
if i mod 3 == 0
{
flag = true
print["Fizz"]
}
if i mod 5 == 0
{
flag = true
print["Buzz"]
}
if flag == false
print[i]
println[]
}
FutureBasic
include "NSLog.incl"
long fizz, buzz, i
for i = 1 to 100
fizz = (i mod 3 )
buzz = (i mod 5 )
if fizz + buzz == 0 then NSLog(@"FizzBuzz") : continue
if fizz == 0 then NSLog(@"Fizz") : continue
if buzz == 0 then NSLog(@"Buzz") : continue
NSLog(@"%ld",i)
next i
HandleEvents
Output:
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
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website, However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
In this page you can see the program(s) related to this task and their results.
Gambas
Click this link to run this code
Public Sub Main()
Dim siCount As Short
Dim sText As String
For siCount = 1 To 100
sText = ""
If siCount Mod 3 = 0 Then sText = "Fizz"
If siCount Mod 5 = 0 Then sText = "Buzz"
If siCount Mod 15 = 0 Then sText = "FizzBuzz"
If sText Then Print sText Else Print siCount
Next
End
Output:
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
GAP
FizzBuzz := function()
local i;
for i in [1 .. 100] do
if RemInt(i, 15) = 0 then
Print("FizzBuzz\n");
elif RemInt(i, 3) = 0 then
Print("Fizz\n");
elif RemInt(i, 5) = 0 then
Print("Buzz\n");
else
Print(i, "\n");
fi;
od;
end;
Genyris
@prefix u "http://www.genyris.org/lang/utilities#"
def fizzbuzz (n)
map-left ^((3 = 'fizz') (5 = 'buzz'))
lambda (d)
cond
(equal? 0 (% n d!left))
d!right
else
''
for n in (range 1 100)
define fb (''(.join (fizzbuzz n)))
u:format "%a\n"
cond
(equal? fb '')
n
else
fb
GFA Basic
' Fizz Buzz
'
FOR i%=1 TO 100
IF i% MOD 15=0
PRINT "FizzBuzz"
ELSE IF i% MOD 3=0
PRINT "Fizz"
ELSE IF i% MOD 5=0
PRINT "Buzz"
ELSE
PRINT i%
ENDIF
NEXT i%
Gleam
import gleam/int
import gleam/io
import gleam/iterator
pub fn main() {
iterator.range(1, 101)
|> iterator.map(to_fizzbuzz)
|> iterator.map(io.println)
|> iterator.run
}
fn to_fizzbuzz(n: Int) -> String {
case n % 3, n % 5 {
0, 0 -> "FizzBuzz"
0, _ -> "Fizz"
_, 0 -> "Buzz"
_, _ -> int.to_string(n)
}
}
Go
switch/case approach
package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ {
switch {
case i%15==0:
fmt.Println("FizzBuzz")
case i%3==0:
fmt.Println("Fizz")
case i%5==0:
fmt.Println("Buzz")
default:
fmt.Println(i)
}
}
}
map approach
package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ {
fmt.Println(map[bool]map[bool]interface{}{
false: {false: i, true: "Fizz"}, true: {false: "Buzz", true: "FizzBuzz"},
}[i%5 == 0][i%3 == 0])
}
}
Golfscript
100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*
Golo
module FizzBuzz
augment java.lang.Integer {
function getFizzAndOrBuzz = |this| -> match {
when this % 15 == 0 then "FizzBuzz"
when this % 3 == 0 then "Fizz"
when this % 5 == 0 then "Buzz"
otherwise this
}
}
function main = |args| {
foreach i in [1..101] {
println(i: getFizzAndOrBuzz())
}
}
Gosu
for (i in 1..100) {
if (i % 3 == 0 && i % 5 == 0) {
print("FizzBuzz")
continue
}
if (i % 3 == 0) {
print("Fizz")
continue
}
if (i % 5 == 0) {
print("Buzz")
continue
}
// default
print(i)
}
One liner version (I added new lines to better readability but when you omit them it's one liner):
// note that compiler reports error (I don't know why) but still it's working
for (i in 1..100) {
print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i)
}
Groovy
1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }
GW-BASIC
See FizzBuzz/Basic
Hare
use fmt;
export fn main() void = {
for (let i = 1z; i <= 100; i += 1) {
fmt::println(
if (i % 15 == 0) "FizzBuzz"
else if (i % 3 == 0) "Fizz"
else if (i % 5 == 0) "Buzz"
else i
)!;
};
};
Haskell
Variant directly implementing the specification:
fizzbuzz :: Int -> String
fizzbuzz x
| f 15 = "FizzBuzz"
| f 3 = "Fizz"
| f 5 = "Buzz"
| otherwise = show x
where
f = (0 ==) . rem x
main :: IO ()
main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]
fizzbuzz :: Int -> String
fizzbuzz n =
'\n' :
if null (fizz ++ buzz)
then show n
else fizz ++ buzz
where
fizz =
if mod n 3 == 0
then "Fizz"
else ""
buzz =
if mod n 5 == 0
then "Buzz"
else ""
main :: IO ()
main = putStr $ concatMap fizzbuzz [1 .. 100]
Does not perform the mod 15 step, extesible to arbitrary addtional tests, ex: [bar| n `mod` 7 == 0].
main = mapM_ (putStrLn . fizzbuzz) [1..100]
fizzbuzz n =
show n <|> [fizz| n `mod` 3 == 0] ++
[buzz| n `mod` 5 == 0]
-- A simple default choice operator.
-- Defaults if both fizz and buzz fail, concats if any succeed.
infixr 0 <|>
d <|> [] = d
_ <|> x = concat x
fizz = "Fizz"
buzz = "Buzz"
Alternate implementation using lazy infinite lists and avoiding use of "mod":
main = mapM_ putStrLn $ take 100 $ zipWith show_number_or_fizzbuzz [1..] fizz_buzz_list
show_number_or_fizzbuzz x y = if null y then show x else y
fizz_buzz_list = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"])
Or in terms (still without mod or rem) of a single zipWith3:
import Data.List (zipWith3)
import Data.Bool (bool)
fizzBuzz :: [String]
fizzBuzz =
zipWith3
(\f b n ->
let fb = f ++ b
in bool fb n (null fb))
(cycle $ replicate 2 [] ++ ["fizz"])
(cycle $ replicate 4 [] ++ ["buzz"])
(show <$> [1 ..])
main :: IO ()
main = mapM_ putStrLn $ take 100 fizzBuzz
or using an applicative test:
import Data.Bool (bool)
fizzBuzz :: [String]
fizzBuzz =
let fb n k = cycle $ replicate (pred n) [] <> [k]
in zipWith
(flip . bool <*> null)
(zipWith (<>) (fb 3 "fizz") (fb 5 "buzz"))
(show <$> [1 ..])
main :: IO ()
main = mapM_ putStrLn $ take 100 fizzBuzz
Using heavy artillery (needs the mtl package):
import Control.Monad.State
import Control.Monad.Trans
import Control.Monad.Writer
main = putStr $ execWriter $ mapM_ (flip execStateT True . fizzbuzz) [1..100]
fizzbuzz :: Int -> StateT Bool (Writer String) ()
fizzbuzz x = do
when (x `mod` 3 == 0) $ tell "Fizz" >> put False
when (x `mod` 5 == 0) $ tell "Buzz" >> put False
get >>= (flip when $ tell $ show x)
tell "\n"
Using guards plus where.
fizzBuzz :: (Integral a) => a -> String
fizzBuzz i
| fizz && buzz = "FizzBuzz"
| fizz = "Fizz"
| buzz = "Buzz"
| otherwise = show i
where fizz = i `mod` 3 == 0
buzz = i `mod` 5 == 0
main = mapM_ (putStrLn . fizzBuzz) [1..100]
An elegant solution exploiting monoidal and applicative properties of functions:
import Data.Monoid
fizzbuzz = max
<$> show
<*> "fizz" `when` divisibleBy 3
<> "buzz" `when` divisibleBy 5
<> "quxx" `when` divisibleBy 7
where
when m p x = if p x then m else mempty
divisibleBy n x = x `mod` n == 0
main = mapM_ (putStrLn . fizzbuzz) [1..100]
And pattern matching approach:
fizzbuzz n = case (rem n 3, rem n 5) of
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
(_, 0) -> "Buzz"
(_, _) -> show n
main = mapM_ (putStrLn . fizzbuzz) [1..100]
Generalised solution:
wordthing :: [(Int, String)] -> Int -> String
wordthing lst n =
if matches == [] then
show n
else
concat $ map snd matches
where matches = filter (\x -> n `mod` (fst x) == 0) lst
fizzbuzz :: Int -> String
fizzbuzz = wordthing [(3, "Fizz"), (5, "Buzz")]
main = do
mapM_ (putStrLn . fizzbuzz) [1..100]
hexiscript
for let i 1; i <= 100; i++
if i % 3 = 0 && i % 5 = 0; println "FizzBuzz"
elif i % 3 = 0; println "Fizz"
elif i % 5 = 0; println "Buzz"
else println i; endif
endfor
HicEst
DO i = 1, 100
IF( MOD(i, 15) == 0 ) THEN
WRITE() "FizzBuzz"
ELSEIF( MOD(i, 5) == 0 ) THEN
WRITE() "Buzz"
ELSEIF( MOD(i, 3) == 0 ) THEN
WRITE() "Fizz"
ELSE
WRITE() i
ENDIF
ENDDO
Alternatively:
CHARACTER string*8
DO i = 1, 100
string = " "
IF( MOD(i, 3) == 0 ) string = "Fizz"
IF( MOD(i, 5) == 0 ) string = TRIM(string) // "Buzz"
IF( string == " ") WRITE(Text=string) i
WRITE() string
ENDDO
HolyC
U8 i;
for (i = 1; i <= 100; i++) {
if (!(i % 15))
Print("FizzBuzz");
else if (!(i % 3))
Print("Fizz");
else if (!(i % 5))
Print("Buzz");
else
Print("%d", i);
Print("\n");
}
Hoon
:- %say
|= [^ ~ ~]
:- %noun
%+ turn (gulf [1 101])
|= a=@
=+ q=[=(0 (mod a 3)) =(0 (mod a 5))]
?+ q <a>
[& &] "FizzBuzz"
[& |] "Fizz"
[| &] "Buzz"
==
Huginn
import Algorithms as algo;
main( argv_ ) {
if ( size( argv_ ) < 2 ) {
throw Exception( "usage: fizzbuzz {NUM}" );
}
top = integer( argv_[1] );
for ( i : algo.range( 1, top + 1 ) ) {
by3 = ( i % 3 ) == 0;
by5 = ( i % 5 ) == 0;
if ( by3 ) {
print( "fizz" );
}
if ( by5 ) {
print( "buzz" );
}
if ( ! ( by3 || by5 ) ) {
print( i );
}
print( "\n" );
}
return ( 0 );
}
Hy
(for [i (range 1 101)] (print (cond
[(not (% i 15)) "FizzBuzz"]
[(not (% i 5)) "Buzz"]
[(not (% i 3)) "Fizz"]
[True i])))
i
software {
for each 1 to 100
if i % 15 = 0
print("FizzBuzz")
else if i % 3 = 0
print("Fizz")
else if i % 5 = 0
print("Buzz")
else
print(i)
end
end
}
Icon and Unicon
Idris
partial
fizzBuzz : Nat -> String
fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz"
else if (n `modNat` 3) == 0 then "Fizz"
else if (n `modNat` 5) == 0 then "Buzz"
else show n
main : IO ()
main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]
Inform 6
[ Main i;
for(i = 1: i <= 100: i++)
{
if(i % 3 == 0) print "Fizz";
if(i % 5 == 0) print "Buzz";
if(i % 3 ~= 0 && i % 5 ~= 0) print i;
print "^";
}
];
Inform 7
(Does not work in the current version of Inform 7)
Home is a room.
When play begins:
repeat with N running from 1 to 100:
let printed be false;
if the remainder after dividing N by 3 is 0:
say "Fizz";
now printed is true;
if the remainder after dividing N by 5 is 0:
say "Buzz";
now printed is true;
if printed is false, say N;
say ".";
end the story.
(Version which is less "programmy", and more in the natural English style of interactive fiction.)
The space is a room. An item is a kind of thing. In the space are 100 items.
To say the name:
let the count be the number of items carried by the player;
say "[if the count is the count to the nearest 15]fizzbuzz.[otherwise if the count is the count to the nearest 3]fizz.[otherwise if the count is the count to the nearest 5]buzz.[otherwise][the count in words].".
To count:
if an item is in the space
begin;
let the next one be a random item in the space; silently try taking the next one;
say "[the name]" in sentence case;
count;
end the story;
end if.
When play begins: count. Use no scoring.
Io
Here's one way to do it:
for(a,1,100,
if(a % 15 == 0) then(
"FizzBuzz" println
) elseif(a % 3 == 0) then(
"Fizz" println
) elseif(a % 5 == 0) then(
"Buzz" println
) else (
a println
)
)
And here's a port of the Ruby version, which I personally prefer:
a := 0; b := 0
for(n, 1, 100,
if(a = (n % 3) == 0, "Fizz" print);
if(b = (n % 5) == 0, "Buzz" print);
if(a not and b not, n print);
"\n" print
)
And here is another more idiomatic version:
for (n, 1, 100,
fb := list (
if (n % 3 == 0, "Fizz"),
if (n % 5 == 0, "Buzz")) select (isTrue)
if (fb isEmpty, n, fb join) println
)
Ioke
(1..100) each(x,
cond(
(x % 15) zero?, "FizzBuzz" println,
(x % 3) zero?, "Fizz" println,
(x % 5) zero?, "Buzz" println
)
)
Iptscrae
; FizzBuzz in Iptscrae
1 a =
{
"" b =
{ "fizz" b &= } a 3 % 0 == IF
{ "buzz" b &= } a 5 % 0 == IF
{ a ITOA LOGMSG } { b LOGMSG } b STRLEN 0 == IFELSE
a ++
}
{ a 100 <= } WHILE
J
Perhaps the most concise approach would be >((2#.3 q:15&+.){(|.(;~,&;);:'Fizz Buzz');~":)&>1+i.100
(The above is a live link to a browser based implementation of fizzbuzz in J. To see how this expression works, remove the leading > leaving items in boxes rather than on lines by themselves. And, then, replace the { with ; which means that instead of using the left argument to select (index) from a list of boxes, the left argument is appended in a box to the left of those boxes. Perhaps also replace the 100 with 20 to shrink the result size. If you remove the 1+i.20 (or 1+i.100) entirely, that would display as the verb (function) which is applied to each number.)
Other approaches are possible:
Solution _1: Using agenda (@.) as a switch:
classify =: +/@(1 2 * 0 = 3 5&|~)
(":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100
Solution 0
> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101
Solution 1
Fizz=: 'Fizz' #~ 0 = 3&|
Buzz=: 'Buzz' #~ 0 = 5&|
FizzBuzz=: ": [^:('' -: ]) Fizz,Buzz
FizzBuzz"0 >: i.100
Solution 2 (has taste of table-driven template programming)
CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": '
NB. Rather (, 0 = +./) than (, +:/) because designed for
NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7
FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz')
FizzBuzz"0 >: i.100
Solution 3 (depends on an obsolete feature of @ in f`g`h@p)
'`f b fb' =: ('Fizz'"_) ` ('Buzz'"_) ` (f , b)
'`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@)
FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also:
FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5)
FizzBuzz"0 >: i.100
Solution 4 (relatively concise):
;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~ 0 = 3 5 |/ ])i.101
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 Fiz...
Here's some intermediate results for subexpressions of this last version (but with a shorter list of numbers):
i.10
0 1 2 3 4 5 6 7 8 9
(3 5 |/ ])i.10
0 1 2 0 1 2 0 1 2 0
0 1 2 3 4 0 1 2 3 4
(0=3 5 |/ ])i.10
1 0 0 1 0 0 1 0 0 1
1 0 0 0 0 1 0 0 0 0
(;:'Fizz Buzz')
┌────┬────┐
│Fizz│Buzz│
└────┴────┘
((;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌────┬┬┬────┬┬────┬────┬┬┬────┐
│Fizz│││Fizz││ │Fizz│││Fizz│
├────┼┼┼────┼┼────┼────┼┼┼────┤
│Buzz│││ ││Buzz│ │││ │
└────┴┴┴────┴┴────┴────┴┴┴────┘
([: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌────────┬┬┬────┬┬────┬────┬┬┬────┐
│FizzBuzz│││Fizz││Buzz│Fizz│││Fizz│
└────────┴┴┴────┴┴────┴────┴┴┴────┘
(":&.>)i.10
┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
│0│1│2│3│4│5│6│7│8│9│
└─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘
(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌────────┬─┬─┬────┬─┬────┬────┬─┬─┬────┐
│FizzBuzz│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│
└────────┴─┴─┴────┴─┴────┴────┴─┴─┴────┘
}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌─┬─┬────┬─┬────┬────┬─┬─┬────┐
│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│
└─┴─┴────┴─┴────┴────┴─┴─┴────┘
;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
1 2 Fizz 4 Buzz Fizz 7 8 Fizz
Janet
(loop [i :range [1 101]
:let [fizz (zero? (% i 3))
buzz (zero? (% i 5))]]
(print (cond
(and fizz buzz) "fizzbuzz"
fizz "fizz"
buzz "buzz"
i)))
Java
public class FizzBuzz {
public static void main(String[] args) {
for (int number = 1; number <= 100; number++) {
if (number % 15 == 0) {
System.out.println("FizzBuzz");
} else if (number % 3 == 0) {
System.out.println("Fizz");
} else if (number % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(number);
}
}
}
}
Or:
public class FizzBuzz {
public static void main(String[] args) {
int number = 1;
while (number <= 100) {
if (number % 15 == 0) {
System.out.println("FizzBuzz");
} else if (number % 3 == 0) {
System.out.println("Fizz");
} else if (number % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(number);
}
number++;
}
}
}
Or:
public class FizzBuzz {
public static void main(String[] args) {
int number = 1;
while (number <= 100) {
System.out.println(number % 15 == 0 ? "FizzBuzz" : number % 3 == 0 ? "Fizz" : number % 5 == 0 ? "Buzz" : number);
number++;
}
}
}
JavaScript
ES5
var fizzBuzz = function () {
var i, output;
for (i = 1; i < 101; i += 1) {
output = '';
if (!(i % 3)) { output += 'Fizz'; }
if (!(i % 5)) { output += 'Buzz'; }
console.log(output || i);//empty string is false, so we short-circuit
}
};
Alternate version with ghetto pattern matching
for (var i = 1; i <= 100; i++) {
console.log({
truefalse: 'Fizz',
falsetrue: 'Buzz',
truetrue: 'FizzBuzz'
}[(i%3==0) + '' + (i%5==0)] || i)
}
Or very tersely:
for(i=1;i<101;i++)console.log((x=(i%3?'':'Fizz')+(i%5?'':'Buzz'))?x:i);
Or with even less characters:
for(i=1;i<101;i++)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)
Or, in a more functional style, without mutations
(function rng(i) {
return i ? rng(i - 1).concat(i) : []
})(100).map(
function (n) {
return n % 3 ? (
n % 5 ? n : "Buzz"
) : (
n % 5 ? "Fizz" : "FizzBuzz"
)
}
).join(' ')
ES6
(() => {
// FIZZBUZZ --------------------------------------------------------------
// fizzBuzz :: Int -> String
const fizzBuzz = n =>
caseOf(n, [
[x => x % 15 === 0, "FizzBuzz"],
[x => x % 3 === 0, "Fizz"],
[x => x % 5 === 0, "Buzz"]
], n.toString());
// GENERIC FUNCTIONS -----------------------------------------------------
// caseOf :: a -> [(a -> Bool, b)] -> b -> b
const caseOf = (e, pvs, otherwise) =>
pvs.reduce((a, [p, v]) =>
a !== otherwise ? a : (p(e) ? v : a), otherwise);
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// TEST ------------------------------------------------------------------
return unlines(
map(fizzBuzz, enumFromTo(1, 100))
);
})();
A functional implementation:
const factors = [[3, 'Fizz'], [5, 'Buzz']]
const fizzBuzz = num => factors.map(([factor,text]) => (num % factor)?'':text).join('') || num
const range1 = x => [...Array(x+1).keys()].slice(1)
const outputs = range1(100).map(fizzBuzz)
console.log(outputs.join('\n'))
Or composing generic functions, and without use of modulo (or other) numeric tests:
(() => {
'use strict';
// main :: IO ()
const main = () => {
// FIZZBUZZ ---------------------------------------
// fizzBuzz :: Generator [String]
const fizzBuzz = () => {
const fb = n => k => cycle(
replicate(n - 1)('').concat(k)
);
return zipWith(
liftA2(flip)(bool)(isNull)
)(
zipWith(append)(fb(3)('fizz'))(fb(5)('buzz'))
)(fmap(str)(enumFrom(1)));
};
// TEST -------------------------------------------
console.log(
unlines(
take(100)(
fizzBuzz()
)
)
);
};
// GENERIC FUNCTIONS ----------------------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a => b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = xs => ys => xs.concat(ys);
// bool :: a -> a -> Bool -> a
const bool = f => t => p =>
p ? t : f;
// cycle :: [a] -> Generator [a]
function* cycle(xs) {
const lng = xs.length;
let i = 0;
while (true) {
yield(xs[i])
i = (1 + i) % lng;
}
}
// enumFrom :: Int => Int -> [Int]
function* enumFrom(x) {
let v = x;
while (true) {
yield v;
v = 1 + v;
}
}
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
x => y => f(y)(x);
// fmap <$> :: (a -> b) -> Gen [a] -> Gen [b]
const fmap = f =>
function*(gen) {
let v = take(1)(gen);
while (0 < v.length) {
yield(f(v[0]))
v = take(1)(gen)
}
};
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
// isNull :: [a] -> Bool
// isNull :: String -> Bool
const isNull = xs =>
1 > xs.length;
// Returns Infinity over objects without finite length.
// This enables zip and zipWith to choose the shorter
// argument when one is non-finite, like cycle, repeat etc
// length :: [a] -> Int
const length = xs =>
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// liftA2 :: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c
const liftA2 = op => f => g =>
// Lift a binary function to a composition
// over two other functions.
// liftA2 (*) (+ 2) (+ 3) 7 == 90
x => op(f(x))(g(x));
// replicate :: Int -> a -> [a]
const replicate = n => x =>
Array.from({
length: n
}, () => x);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// str :: a -> String
const str = x => x.toString();
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n => xs =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// The first argument is a sample of the type
// allowing the function to make the right mapping
// uncons :: [a] -> Maybe (a, [a])
const uncons = xs => {
const lng = length(xs);
return (0 < lng) ? (
lng < Infinity ? (
Just(Tuple(xs[0])(xs.slice(1))) // Finite list
) : (() => {
const nxt = take(1)(xs);
return 0 < nxt.length ? (
Just(Tuple(nxt[0])(xs))
) : Nothing();
})() // Lazy generator
) : Nothing();
};
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// zipWith :: (a -> b -> c) Gen [a] -> Gen [b] -> Gen [c]
const zipWith = f => ga => gb => {
function* go(ma, mb) {
let
a = ma,
b = mb;
while (!a.Nothing && !b.Nothing) {
let
ta = a.Just,
tb = b.Just
yield(f(fst(ta))(fst(tb)));
a = uncons(snd(ta));
b = uncons(snd(tb));
}
}
return go(uncons(ga), uncons(gb));
};
// MAIN ---
return main();
})();
Joy
The following program first defines a function "out", that handles the Fizz / Buzz logic, and then loops from 1 to 100 mapping the function onto each number, and printing ("put") the output.
DEFINE out == [[[15 rem null] "FizzBuzz"]
[[ 3 rem null] "Fizz"]
[[ 5 rem null] "Buzz"]
[]] cond
[putchars pop] [put] ifstring '\n putch.
100 [] [out] primrec.
jq
range(1;101)
| if . % 15 == 0 then "FizzBuzz"
elif . % 5 == 0 then "Buzz"
elif . % 3 == 0 then "Fizz"
else .
end
Another solution:
range(100) + 1 | [(
(select(. % 3 == 0) | "Fizz"),
(select(. % 5 == 0) | "Buzz")
) // tostring] | join("")
Julia
One basic solution:
for i in 1:100
if i % 15 == 0
println("FizzBuzz")
elseif i % 3 == 0
println("Fizz")
elseif i % 5 == 0
println("Buzz")
else
println(i)
end
end
Another possible solution:
collect(i % 15 == 0 ? "FizzBuzz" : i % 5 == 0 ? "Buzz" : i % 3 == 0 ? "Fizz" : i for i in 1:100) |> println
A 3rd possible solution:
fb(i::Integer) = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) * dec(i) ^ (i % 3 != 0 && i % 5 != 0)
for i in 1:100 println(fb(i)) end
A 4th one:
println.(map(fb, 1:100))
A fifth (DRY, Don't Repeat Yourself) possible solution:
for i in 1:100
msg = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0)
println(isempty(msg) ? i : msg)
end
K
Solution 0
`0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101
Solution 1
fizzbuzz:{:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]}
fizzbuzz' 1+!100
Solution 2
fizzbuzz:{
v:1+!x
i:(&0=)'v!/:3 5 15
r:@[v;i 0;{"Fizz"}]
r:@[r;i 1;{"Buzz"}]
@[r;i 2;{"FizzBuzz"}]}
`0:$fizzbuzz 100
Solution 3
For kona:
{,/$(s;x)@~#s:`Fizz`Buzz@&~x!'3 5}'1+!30
For k6 and oK, change x!'3 5
to 3 5!'x
.
Kamailio Script
To run it, send a SIP message to the server and FizzBuzz will appear in the logs.
This will only work up to 100 because Kamailio terminates all while loops after 100 iterations.
# FizzBuzz
log_stderror=yes
loadmodule "pv"
loadmodule "xlog"
route {
$var(i) = 1;
while ($var(i) <= 1000) {
if ($var(i) mod 15 == 0) {
xlog("FizzBuzz\n");
} else if ($var(i) mod 5 == 0) {
xlog("Buzz\n");
} else if ($var(i) mod 3 == 0) {
xlog("Fizz\n");
} else {
xlog("$var(i)\n");
}
$var(i) = $var(i) + 1;
}
}
Kaya
// fizzbuzz in Kaya
program fizzbuzz;
Void fizzbuzz(Int size) {
for i in [1..size] {
if (i % 15 == 0) {
putStrLn("FizzBuzz");
} else if (i % 5 == 0) {
putStrLn("Buzz");
} else if (i % 3 == 0) {
putStrLn("Fizz");
} else {
putStrLn( string(i) );
}
}
}
Void main() {
fizzbuzz(100);
}
KL1
:- module main.
main :-
nats(100, Nats),
fizzbuzz(Nats, Output),
display(Output).
nats(Max, Out) :-
nats(Max, 1, Out).
nats(Max, Count, Out) :- Count =< Max |
Out = [Count|NewOut],
NewCount := Count + 1,
nats(Max, NewCount, NewOut).
nats(Max, Count, Out) :- Count > Max |
Out = [].
fizzbuzz([N|Rest], Out) :- N mod 3 =:= 0, N mod 5 =:= 0 |
Out = ['FizzBuzz' | NewOut],
fizzbuzz(Rest, NewOut).
fizzbuzz([], Out) :-
Out = [].
alternatively.
fizzbuzz([N|Rest], Out) :- N mod 3 =:= 0 |
Out = ['Fizz' | NewOut],
fizzbuzz(Rest, NewOut).
fizzbuzz([N|Rest], Out) :- N mod 5 =:= 0 |
Out = ['Buzz' | NewOut],
fizzbuzz(Rest, NewOut).
alternatively.
fizzbuzz([N|Rest], Out) :-
Out = [N | NewOut],
fizzbuzz(Rest, NewOut).
display([Message|Rest]) :-
io:outstream([print(Message), nl]),
display(Rest).
display([]).
Klong
{:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100
Kotlin
Imperative solution
fun fizzBuzz() {
for (number in 1..100) {
println(
when {
number % 15 == 0 -> "FizzBuzz"
number % 3 == 0 -> "Fizz"
number % 5 == 0 -> "Buzz"
else -> number
}
)
}
}
Functional solution 1
fun fizzBuzz1() {
fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString()
fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x
fun buzz(x: Any) = if (x is Int && x.toInt() % 5 == 0) "Fizz" else x
(1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) }
}
Functional solution 2
fun fizzBuzz2() {
fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x
fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x
fun none(x: Pair<Int, StringBuilder>) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second
(1..100).map { Pair(it, StringBuilder()) }
.map { fizz(it) }
.map { buzz(it) }
.map { none(it) }
.forEach { println(it) }
}
Short version with mapOf
fun fizzBuzz() {
(1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) }
}
KQL
range i from 1 to 100 step 1
| project Result =
case(
i % 15 == 0, "FizzBuzz",
i % 3 == 0, "Fizz",
i % 5 == 0, "Buzz",
tostring(i)
)
KSI
`plain
[1 100] `for pos : n ~
out = []
n `mod 3 == 0 ? out.# = 'Fizz' ;
n `mod 5 == 0 ? out.# = 'Buzz' ;
(out `or n) #write_ln #
;
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lambdatalk
1. direct:
{S.map
{lambda {:i}
{if {= {% :i 15} 0}
then fizzbuzz
else {if {= {% :i 3} 0}
then fizz
else {if {= {% :i 5} 0}
then buzz
else :i}}}}
{S.serie 1 100}}
-> 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
2. via a function
{def fizzbuzz
{lambda {:i :n}
{if {> :i :n}
then .
else {if {= {% :i 15} 0}
then fizzbuzz
else {if {= {% :i 3} 0}
then fizz
else {if {= {% :i 5} 0}
then buzz
else :i}}} {fizzbuzz {+ :i 1} :n}
}}}
-> fizzbuzz
{fizzbuzz 1 100}
-> same as above.
langur
for .i of 100 {
writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i)
}
for .i of 100 {
writeln if(.i div 15: "FizzBuzz"; .i div 5: "Buzz"; .i div 3: "Fizz"; .i)
}
Lasso
with i in generateSeries(1, 100)
select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)
LaTeX
This version uses the ifthen and intcalc packages. There sure are more native solutions including solutions in plain TeX, but for me this is a readable and comprehensible one.
\documentclass{minimal}
\usepackage{ifthen}
\usepackage{intcalc}
\newcounter{mycount}
\newboolean{fizzOrBuzz}
\newcommand\fizzBuzz[1]{%
\setcounter{mycount}{1}\whiledo{\value{mycount}<#1}
{
\setboolean{fizzOrBuzz}{false}
\ifthenelse{\equal{\intcalcMod{\themycount}{3}}{0}}{\setboolean{fizzOrBuzz}{true}Fizz}{}
\ifthenelse{\equal{\intcalcMod{\themycount}{5}}{0}}{\setboolean{fizzOrBuzz}{true}Buzz}{}
\ifthenelse{\boolean{fizzOrBuzz}}{}{\themycount}
\stepcounter{mycount}
\\
}
}
\begin{document}
\fizzBuzz{101}
\end{document}
Liberty BASIC
See FizzBuzz/Basic
LIL
# fizzbuzz in LIL
for {set i 1} {$i <= 100} {inc i} {
set show ""
if {[expr $i % 3 == 0]} {set show "Fizz"}
if {[expr $i % 5 == 0]} {set show $show"Buzz"}
if {[expr [length $show] == 0]} {set show $i}
print $show
}
- Output:
prompt$ lil fizzbuzz.lil | sed -n '1,16p' 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16
LiveCode
repeat with i = 1 to 100
switch
case i mod 15 = 0
put "FizzBuzz" & cr after fizzbuzz
break
case i mod 5 = 0
put "Buzz" & cr after fizzbuzz
break
case i mod 3 = 0
put "Fizz" & cr after fizzbuzz
break
default
put i & cr after fizzbuzz
end switch
end repeat
put fizzbuzz
LiveScript
See: http://livescript.net/blog/fizzbuzzbazz.html
[1 to 100] map -> [k + \zz for k, v of {Fi: 3, Bu: 5} | it % v < 1] * '' || it
LLVM
; ModuleID = 'fizzbuzz.c'
; source_filename = "fizzbuzz.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
; target triple = "x86_64-pc-windows-msvc19.21.27702"
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
$"\01??_C@_09NODAFEIA@FizzBuzz?6?$AA@" = comdat any
$"\01??_C@_05KEBFOHOF@Fizz?6?$AA@" = comdat any
$"\01??_C@_05JKJENPHA@Buzz?6?$AA@" = comdat any
$"\01??_C@_03PMGGPEJJ@?$CFd?6?$AA@" = comdat any
;--- String constant defintions
@"\01??_C@_09NODAFEIA@FizzBuzz?6?$AA@" = linkonce_odr unnamed_addr constant [10 x i8] c"FizzBuzz\0A\00", comdat, align 1
@"\01??_C@_05KEBFOHOF@Fizz?6?$AA@" = linkonce_odr unnamed_addr constant [6 x i8] c"Fizz\0A\00", comdat, align 1
@"\01??_C@_05JKJENPHA@Buzz?6?$AA@" = linkonce_odr unnamed_addr constant [6 x i8] c"Buzz\0A\00", comdat, align 1
@"\01??_C@_03PMGGPEJJ@?$CFd?6?$AA@" = linkonce_odr unnamed_addr constant [4 x i8] c"%d\0A\00", comdat, align 1
;--- The declaration for the external C printf function.
declare i32 @printf(i8*, ...)
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
store i32 1, i32* %1, align 4
;--- It does not seem like this branch can be removed
br label %loop
;--- while (i <= 100)
loop:
%2 = load i32, i32* %1, align 4
%3 = icmp sle i32 %2, 100
br i1 %3, label %divisible_15, label %finished
;--- if (i % 15 == 0)
divisible_15:
%4 = load i32, i32* %1, align 4
%5 = srem i32 %4, 15
%6 = icmp eq i32 %5, 0
br i1 %6, label %print_fizzbuzz, label %divisible_3
;--- Print 'FizzBuzz'
print_fizzbuzz:
%7 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01??_C@_09NODAFEIA@FizzBuzz?6?$AA@", i32 0, i32 0))
br label %next
;--- if (i % 3 == 0)
divisible_3:
%8 = load i32, i32* %1, align 4
%9 = srem i32 %8, 3
%10 = icmp eq i32 %9, 0
br i1 %10, label %print_fizz, label %divisible_5
;--- Print 'Fizz'
print_fizz:
%11 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01??_C@_05KEBFOHOF@Fizz?6?$AA@", i32 0, i32 0))
br label %next
;--- if (i % 5 == 0)
divisible_5:
%12 = load i32, i32* %1, align 4
%13 = srem i32 %12, 5
%14 = icmp eq i32 %13, 0
br i1 %14, label %print_buzz, label %print_number
;--- Print 'Buzz'
print_buzz:
%15 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01??_C@_05JKJENPHA@Buzz?6?$AA@", i32 0, i32 0))
br label %next
;--- Print the number
print_number:
%16 = load i32, i32* %1, align 4
%17 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01??_C@_03PMGGPEJJ@?$CFd?6?$AA@", i32 0, i32 0), i32 %16)
;--- It does not seem like this branch can be removed
br label %next
;--- i = i + 1
next:
%18 = load i32, i32* %1, align 4
%19 = add nsw i32 %18, 1
store i32 %19, i32* %1, align 4
br label %loop
;--- exit main
finished:
ret i32 0
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
!llvm.module.flags = !{!0, !1}
!llvm.ident = !{!2}
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}
Lobster
include "std.lobster"
forbias(100, 1) i:
fb := (i % 3 == 0 and "fizz" or "") +
(i % 5 == 0 and "buzz" or "")
print fb.length and fb or "" + i
Logo
to fizzbuzz :n
output cond [ [[equal? 0 modulo :n 15] "FizzBuzz]
[[equal? 0 modulo :n 5] "Buzz]
[[equal? 0 modulo :n 3] "Fizz]
[else :n] ]
end
repeat 100 [print fizzbuzz #]
"cond" was undefined in Joshua Bell's online interpreter. So here is a version that works there. It also works in UCB logo by using # instead of "repcount". This version also factors away modulo 15:
to fizzbuzz :n
make "c "
if equal? 0 modulo :n 5 [make "c "Buzz]
if equal? 0 modulo :n 3 [make "c word "Fizz :c]
output ifelse equal? :c " [:n] [:c]
end
repeat 100 [print fizzbuzz repcount]
Lhogho can use the above code, except that 'modulo' must be replaced with 'remainder'.
LOLCODE
See FizzBuzz/EsoLang
LSE
1* FIZZBUZZ en L.S.E.
10 CHAINE FB
20 FAIRE 45 POUR I_1 JUSQUA 100
30 FB_SI &MOD(I,3)=0 ALORS SI &MOD(I,5)=0 ALORS 'FIZZBUZZ' SINON 'FIZZ' SINON SI &MOD(I,5)=0 ALORS 'BUZZ' SINON ''
40 AFFICHER[U,/] SI FB='' ALORS I SINON FB
45*FIN BOUCLE
50 TERMINER
100 PROCEDURE &MOD(A,B) LOCAL A,B
110 RESULTAT A-B*ENT(A/B)
Lua
If/else Ladder
for i = 1, 100 do
if i % 15 == 0 then
print("FizzBuzz")
elseif i % 3 == 0 then
print("Fizz")
elseif i % 5 == 0 then
print("Buzz")
else
print(i)
end
end
Concatenation
for i = 1, 100 do
output = ""
if i % 3 == 0 then
output = output.."Fizz"
end
if i % 5 == 0 then
output = output.."Buzz"
end
if(output == "") then
output = i
end
print(output)
end
Quasi bit field
word = {"Fizz", "Buzz", "FizzBuzz"}
for i = 1, 100 do
print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i)
end
Lookup table
local t = {
[0] = "FizzBuzz",
[3] = "Fizz",
[5] = "Buzz",
[6] = "Fizz",
[9] = "Fizz",
[10] = "Buzz",
[12] = "Fizz"
}
for i = 1, 100 do
print(t[i%15] or i)
end
Fast Version without Modulo
#!/usr/bin/env luajit
local to=arg[1] or tonumber(arg[1]) or 100
local CF,CB=3,5
local cf,cb=CF,CB
for i=1,to do
cf,cb=cf-1,cb-1
if cf~=0 and cb~=0 then
io.write(i)
else
if cf==0 then
cf=CF
io.write("Fizz")
end
if cb==0 then
cb=CB
io.write("Buzz")
end
end
io.write(", ")
end
- Output:
> ./fizzbuzz.lua 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, %
Luck
for i in range(1,101) do (
if i%15 == 0 then print("FizzBuzz")
else if i%3 == 0 then print("Fizz")
else if i%5 == 0 then print("Buzz")
else print(i)
)
M2000 Interpreter
\\ one line, hard to read
For i=1 to 100 {If i mod 3=0 Then {if i mod 5=0 Then Print "FizzBuzz", Else Print "Fizz",} Else {if i mod 5=0 Then Print "Buzz", else print i, } } : Print
\\ Better code
For i=1 to 100 {
Push str$(i,0)+". "+if$(i mod 3=0->"Fizz","")+if$(i mod 5=0->"Buzz","")
If stackitem$()="" then Drop : Continue
Print Letter$
}
\\ Far Better Code
For i=1 to 100 {
Printme(if$(i mod 3=0->"Fizz","")+if$(i mod 5=0->"Buzz",""))
}
Print
Sub Printme(a$)
If a$<>"" Then Print a$, else Print i,
End Sub
M4
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')
for(`x',1,100,1,
`ifelse(eval(x%15==0),1,FizzBuzz,
`ifelse(eval(x%3==0),1,Fizz,
`ifelse(eval(x%5==0),1,Buzz,x)')')
')
make
MOD3 = 0
MOD5 = 0
ALL != jot 100
all: say-100
.for NUMBER in $(ALL)
MOD3 != expr \( $(MOD3) + 1 \) % 3; true
MOD5 != expr \( $(MOD5) + 1 \) % 5; true
. if "$(NUMBER)" > 1
PRED != expr $(NUMBER) - 1
say-$(NUMBER): say-$(PRED)
. else
say-$(NUMBER):
. endif
. if "$(MOD3)$(MOD5)" == "00"
@echo FizzBuzz
. elif "$(MOD3)" == "0"
@echo Fizz
. elif "$(MOD5)" == "0"
@echo Buzz
. else
@echo $(NUMBER)
. endif
.endfor
Maple
One line:
seq(print(`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n))),n=1..100):
With a fizzbuzz function defined:
fizzbuzz1 := n->`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n)):
for i to 100 do fizzbuzz1(i); od;
Using piecewise:
fizzbuzz2 := n->piecewise(modp(n,15)=0,"FizzBuzz",modp(n,3)=0,"Fizz",modp(n,5)=0,"Buzz",n):
for i to 100 do fizzbuzz2(i); od;
Using conventional if/then branches:
fizzbuzz3 := proc(n) local r;
r:=map2(modp,n,[3,5]);
if r=[0,0] then "FizzBuzz"
elif r[1]=0 then "Fizz"
elif r[2]=0 then "Buzz"
else n fi;
end proc:
for i to 100 do fizzbuzz3(i); od;
Mathematica / Wolfram Language
Do[Print[Which[Mod[i, 15] == 0, "FizzBuzz", Mod[i, 5] == 0, "Buzz", Mod[i, 3] == 0, "Fizz", True, i]], {i, 100}]
Using rules,
fizz[i_] := Mod[i, 3] == 0
buzz[i_] := Mod[i, 5] == 0
Range[100] /. {i_ /; fizz[i]&&buzz[i] :> "FizzBuzz", \
i_?fizz :> "Fizz", i_?buzz :> "Buzz"}
Using rules, but different approach:
SetAttributes[f,Listable]
f[n_ /; Mod[n, 15] == 0] := "FizzBuzz";
f[n_ /; Mod[n, 3] == 0] := "Fizz";
f[n_ /; Mod[n, 5] == 0] := "Buzz";
f[n_] := n;
f[Range[100]]
An extendible version using Table
Table[If[# === "", i, #]&@StringJoin[
Table[If[Divisible[i, First@nw], Last@nw, ""],
{nw, {{3, "Fizz"}, {5, "Buzz"}}}]],
{i, 1, 100}]
Another one-liner using Map (the /@ operator shorthand of it) and a pure function with a very readable Which
Which[ Mod[#,15] == 0, "FizzBuzz", Mod[#, 3] == 0, "Fizz", Mod[#,5]==0, "Buzz", True, #]& /@ Range[1,100]
MATLAB
There are more sophisticated solutions to this task, but in the spirit of "lowest level of comprehension required to illustrate adequacy" this is what one might expect from a novice programmer (with a little variation in how the strings are stored and displayed).
function fizzBuzz()
for i = (1:100)
if mod(i,15) == 0
fprintf('FizzBuzz ')
elseif mod(i,3) == 0
fprintf('Fizz ')
elseif mod(i,5) == 0
fprintf('Buzz ')
else
fprintf('%i ',i))
end
end
fprintf('\n');
end
Here's a more extendible version that uses disp() to print the output:
function out = fizzbuzzS()
nums = [3, 5];
words = {'fizz', 'buzz'};
for (n=1:100)
tempstr = '';
for (i = 1:2)
if mod(n,nums(i))==0
tempstr = [tempstr, words{i}];
end
end
if length(tempstr) == 0
disp(n);
else
disp(tempstr);
end
end
end
Maxima
for n:1 thru 100 do
if mod(n, 15) = 0 then (sprint("FizzBuzz"), newline())
elseif mod(n, 3) = 0 then (sprint("Fizz"), newline())
elseif mod(n,5) = 0 then (sprint("Buzz"), newline())
else (sprint(n), newline());
MAXScript
for i in 1 to 100 do
(
case of
(
(mod i 15 == 0): (print "FizzBuzz")
(mod i 5 == 0): (print "Buzz")
(mod i 3 == 0): (print "Fizz")
default: (print i)
)
)
MEL
for($i=1; $i<=100; $i++)
{
if($i % 15 == 0)
print "FizzBuzz\n";
else if ($i % 3 == 0)
print "Fizz\n";
else if ($i % 5 == 0)
print "Buzz\n";
else
print ($i + "\n");
}
Mercury
:- module fizzbuzz.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, string, bool.
:- func fizz(int) = bool.
fizz(N) = ( if N mod 3 = 0 then yes else no ).
:- func buzz(int) = bool.
buzz(N) = ( if N mod 5 = 0 then yes else no ).
% N 3? 5?
:- func fizzbuzz(int, bool, bool) = string.
fizzbuzz(_, yes, yes) = "FizzBuzz".
fizzbuzz(_, yes, no) = "Fizz".
fizzbuzz(_, no, yes) = "Buzz".
fizzbuzz(N, no, no) = from_int(N).
main(!IO) :- main(1, 100, !IO).
:- pred main(int::in, int::in, io::di, io::uo) is det.
main(N, To, !IO) :-
io.write_string(fizzbuzz(N, fizz(N), buzz(N)), !IO),
io.nl(!IO),
( if N < To then
main(N + 1, To, !IO)
else
true
).
Metafont
for i := 1 upto 100:
message if i mod 15 = 0: "FizzBuzz" &
elseif i mod 3 = 0: "Fizz" &
elseif i mod 5 = 0: "Buzz" &
else: decimal i & fi "";
endfor
end
Microsoft Small Basic
For n = 1 To 100
op = ""
If Math.Remainder(n, 3) = 0 Then
op = "Fizz"
EndIf
IF Math.Remainder(n, 5) = 0 Then
op = text.Append(op, "Buzz")
EndIf
If op = "" Then
TextWindow.WriteLine(n)
Else
TextWindow.WriteLine(op)
EndIf
EndFor
min
0 (
succ false :hit
(3 mod 0 ==) ("Fizz" print! true @hit) when
(5 mod 0 ==) ("Buzz" print! true @hit) when
(hit) (print) unless newline
) 100 times
MiniScript
for i in range(1,100)
if i % 15 == 0 then
print "FizzBuzz"
else if i % 3 == 0 then
print "Fizz"
else if i % 5 == 0 then
print "Buzz"
else
print i
end if
end for
MIPS Assembly
#################################
# Fizz Buzz #
# MIPS Assembly targetings MARS #
# By Keith Stellyes #
# August 24, 2016 #
#################################
# $a0 left alone for printing
# $a1 stores our counter
# $a2 is 1 if not evenly divisible
.data
fizz: .asciiz "Fizz\n"
buzz: .asciiz "Buzz\n"
fizzbuzz: .asciiz "FizzBuzz\n"
newline: .asciiz "\n"
.text
loop:
beq $a1,100,exit
add $a1,$a1,1
#test for counter mod 15 ("FIZZBUZZ")
div $a2,$a1,15
mfhi $a2
bnez $a2,loop_not_fb #jump past the fizzbuzz print logic if NOT MOD 15
#### PRINT FIZZBUZZ: ####
li $v0,4 #set syscall arg to PRINT_STRING
la $a0,fizzbuzz #set the PRINT_STRING arg to fizzbuzz
syscall #call PRINT_STRING
j loop #return to start
#### END PRINT FIZZBUZZ ####
loop_not_fb:
div $a2,$a1,3 #divide $a1 (our counter) by 3 and store remainder in HI
mfhi $a2 #retrieve remainder (result of MOD)
bnez $a2, loop_not_f #jump past the fizz print logic if NOT MOD 3
#### PRINT FIZZ ####
li $v0,4
la $a0,fizz
syscall
j loop
#### END PRINT FIZZ ####
loop_not_f:
div $a2,$a1,5
mfhi $a2
bnez $a2,loop_not_b
#### PRINT BUZZ ####
li $v0,4
la $a0,buzz
syscall
j loop
#### END PRINT BUZZ ####
loop_not_b:
#### PRINT THE INTEGER ####
li $v0,1 #set syscall arg to PRINT_INTEGER
move $a0,$a1 #set PRINT_INTEGER arg to contents of $a1
syscall #call PRINT_INTEGER
### PRINT THE NEWLINE CHAR ###
li $v0,4 #set syscall arg to PRINT_STRING
la $a0,newline
syscall
j loop #return to beginning
exit:
li $v0,10
syscall
Mirah
1.upto(100) do |n|
print "Fizz" if a = ((n % 3) == 0)
print "Buzz" if b = ((n % 5) == 0)
print n unless (a || b)
print "\n"
end
A little more straight forward:
1.upto(100) do |n|
if (n % 15) == 0
puts "FizzBuzz"
elsif (n % 5) == 0
puts "Buzz"
elsif (n % 3) == 0
puts "Fizz"
else
puts n
end
end
ML
Standard ML
First using two helper functions, one for deciding what to output and another for performing recursion with an auxiliary argument j.
local
fun fbstr i =
case (i mod 3 = 0, i mod 5 = 0) of
(true , true ) => "FizzBuzz"
| (true , false) => "Fizz"
| (false, true ) => "Buzz"
| (false, false) => Int.toString i
fun fizzbuzz' (n, j) =
if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1))
in
fun fizzbuzz n = fizzbuzz' (n, 1)
val _ = fizzbuzz 100
end
Second using the standard-library combinator List.tabulate and a helper function, fb, that calculates and prints the output.
local
fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true)
val buzz = i mod 5 = 0 andalso (print "Buzz"; true)
in fizz orelse buzz orelse (print (Int.toString i); true) end
in
fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ())
val _ = fizzbuzz 100
end
mLite
local
fun fizzbuzz'
(x mod 15 = 0) = "FizzBuzz"
| (x mod 5 = 0) = "Buzz"
| (x mod 3 = 0) = "Fizz"
| x = ntos x
in
fun fizzbuzz
([], s) = rev s
| (x :: xs, s) = fizzbuzz (xs, fizzbuzz' x :: s)
| (x :: xs) = fizzbuzz (x :: xs, [])
end
;
println ` fizzbuzz ` iota 100;
MMIX
t IS $255
Ja IS $127
LOC Data_Segment
data GREG @
fizz IS @-Data_Segment
BYTE "Fizz",0,0,0,0
buzz IS @-Data_Segment
BYTE "Buzz",0,0,0,0
nl IS @-Data_Segment
BYTE #a,0,0,0,0,0,0,0
buffer IS @-Data_Segment
LOC #1000
GREG @
% "usual" print integer subroutine
printnum LOC @
OR $1,$0,0
SETL $2,buffer+64
ADDU $2,$2,data
XOR $3,$3,$3
STBU $3,$2,1
loop DIV $1,$1,10
GET $3,rR
ADDU $3,$3,'0'
STBU $3,$2,0
SUBU $2,$2,1
PBNZ $1,loop
ADDU t,$2,1
TRAP 0,Fputs,StdOut
GO Ja,Ja,0
Main SETL $0,1 % i = 1
1H SETL $2,0 % fizz not taken
CMP $1,$0,100 % i <= 100
BP $1,4F % if no, go to end
DIV $1,$0,3
GET $1,rR % $1 = mod(i,3)
CSZ $2,$1,1 % $2 = Fizz taken?
BNZ $1,2F % $1 != 0? yes, then skip
ADDU t,data,fizz
TRAP 0,Fputs,StdOut % print "Fizz"
2H DIV $1,$0,5
GET $1,rR % $1 = mod(i,5)
BNZ $1,3F % $1 != 0? yes, then skip
ADDU t,data,buzz
TRAP 0,Fputs,StdOut % print "Buzz"
JMP 5F % skip print i
3H BP $2,5F % skip if Fizz was taken
GO Ja,printnum % print i
5H ADDU t,data,nl
TRAP 0,Fputs,StdOut % print newline
ADDU $0,$0,1
JMP 1B % repeat for next i
4H XOR t,t,t
TRAP 0,Halt,0 % exit(0)
Modula-2
MODULE Fizzbuzz;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE CB = PROCEDURE(INTEGER);
PROCEDURE Fizz(n : INTEGER);
BEGIN
IF n MOD 3 = 0 THEN
WriteString("Fizz");
Buzz(n,Newline)
ELSE
Buzz(n,WriteInt)
END
END Fizz;
PROCEDURE Buzz(n : INTEGER; f : CB);
BEGIN
IF n MOD 5 = 0 THEN
WriteString("Buzz");
WriteLn
ELSE
f(n)
END
END Buzz;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
FormatString("%i\n", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE Newline(n : INTEGER);
BEGIN
WriteLn
END Newline;
VAR i : INTEGER;
BEGIN
FOR i:=1 TO 30 DO
Fizz(i)
END;
ReadChar
END Fizzbuzz.
Modula-3
MODULE Fizzbuzz EXPORTS Main;
IMPORT IO;
BEGIN
FOR i := 1 TO 100 DO
IF i MOD 15 = 0 THEN
IO.Put("FizzBuzz\n");
ELSIF i MOD 5 = 0 THEN
IO.Put("Buzz\n");
ELSIF i MOD 3 = 0 THEN
IO.Put("Fizz\n");
ELSE
IO.PutInt(i);
IO.Put("\n");
END;
END;
END Fizzbuzz.
Monte
def fizzBuzz(top):
var t := 1
while (t < top):
if ((t % 3 == 0) || (t % 5 == 0)):
if (t % 15 == 0):
traceln(`$t FizzBuzz`)
else if (t % 3 == 0):
traceln(`$t Fizz`)
else:
traceln(`$t Buzz`)
t += 1
fizzBuzz(100)
MontiLang
&DEFINE LOOP 100&
1 VAR i .
FOR LOOP
|| VAR ln .
i 5 % 0 ==
IF : .
ln |Buzz| + VAR ln .
ENDIF
i 3 % 0 ==
IF : .
ln |Fizz| + VAR ln .
ENDIF
ln || ==
IF : .
i PRINT .
ENDIF
ln || !=
IF : .
ln PRINT .
ENDIF
i 1 + VAR i .
ENDFOR
MoonScript
for i = 1,100
print ((a) -> a == "" and i or a) table.concat {
i % 3 == 0 and "Fizz" or ""
i % 5 == 0 and "Buzz" or ""}
MUMPS
FIZZBUZZ
NEW I
FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I)
KILL I
QUIT
fizzbuzz
for i=1:1:100 do write !
. write:(i#3)&(i#5) i write:'(i#3) "Fizz" write:'(i#5) "Buzz"
Nanoquery
for i in range(1, 100)
if ((i % 3) = 0) and ((i % 5) = 0)
println "FizzBuzz"
else if i % 3 = 0
println "Fizz"
else if i % 5 = 0
println "Buzz"
else
println i
end
end
NATURAL
DEFINE DATA
LOCAL
1 #I (I4)
1 #MODULO (I4)
1 #DIVISOR (I4)
1 #OUT (A10)
END-DEFINE
*
FOR #I := 1 TO 100
#DIVISOR := 15
#OUT := 'FizzBuzz'
PERFORM MODULO
*
#DIVISOR := 5
#OUT := 'Buzz'
PERFORM MODULO
*
#DIVISOR := 3
#OUT := 'Fizz'
PERFORM MODULO
*
WRITE #I
END-FOR
*
DEFINE SUBROUTINE MODULO
#MODULO := #I - (#I / #DIVISOR) * #DIVISOR
IF #MODULO = 0
WRITE NOTITLE #OUT
ESCAPE TOP
END-IF
END-SUBROUTINE
*
END
Neko
var i = 1
while(i < 100) {
if(i % 15 == 0) {
$print("FizzBuzz\n");
} else if(i % 3 == 0) {
$print("Fizz\n");
} else if(i % 5 == 0) {
$print("Buzz\n");
} else {
$print(i + "\n");
}
i ++= 1
}
Nemerle
The naive approach:
using System;
using System.Console;
module FizzBuzz
{
FizzBuzz(x : int) : string
{
|x when x % 15 == 0 => "FizzBuzz"
|x when x % 5 == 0 => "Buzz"
|x when x % 3 == 0 => "Fizz"
|_ => $"$x"
}
Main() : void
{
foreach (i in [1 .. 100])
WriteLine($"$(FizzBuzz(i))")
}
}
A much slicker approach is posted here
NetRexx
loop j=1 for 100
select
when j//15==0 then say 'FizzBuzz'
when j//5==0 then say 'Buzz'
when j//3==0 then say 'Fizz'
otherwise say j.right(4)
end
end
Never
func fizz_buzz() -> int
{
var i = 1;
for (i = 1; i <= 100; i = i + 1)
{
/* if (i % 15 == 0) */
if (i % 3 == 0 && i % 5 == 0)
{
prints("Fizz Buzz\n")
}
else if (i % 3 == 0)
{
prints("Fizz\n")
}
else if (i % 5 == 0)
{
prints("Buzz\n")
}
else
{
prints(i + "\n")
}
};
0
}
func main() -> int {
fizz_buzz();
0
}
- Output:
prompt$ never -f fizzbuzz.nev 2>/dev/null 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 Fizz Buzz 16 ... 89 Fizz Buzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
NewLISP
(dotimes (i 100)
(println
(cond
((= 0 (% i 15)) "FizzBuzz")
((= 0 (% i 3)) "Fizz")
((= 0 (% i 5)) "Buzz")
('t i))))
NewtonScript
for i := 1 to 100 do
begin
if i mod 15 = 0 then
print("FizzBuzz")
else if i mod 3 = 0 then
print("Fizz")
else if i mod 5 = 0 then
print("Buzz")
else
print(i);
print("\n")
end
Nickle
/* Fizzbuzz in nickle */
void function fizzbuzz(size) {
for (int i = 1; i < size; i++) {
if (i % 15 == 0) { printf("Fizzbuzz\n"); }
else if (i % 5 == 0) { printf("Buzz\n"); }
else if (i % 3 == 0) { printf("Fizz\n"); }
else { printf("%i\n", i); }
}
}
fizzbuzz(1000);
Nim
for i in 1..100:
if i mod 15 == 0:
echo("FizzBuzz")
elif i mod 3 == 0:
echo("Fizz")
elif i mod 5 == 0:
echo("Buzz")
else:
echo(i)
Without Modulus
var messages = @["", "Fizz", "Buzz", "FizzBuzz"]
var acc = 810092048
for i in 1..100:
var c = acc and 3
echo(if c == 0: $i else: messages[c])
acc = acc shr 2 or c shl 28
Using macro
Computes everything at compile time.
import macros
macro FizzBuzz(N): untyped =
var source = ""
for i in 1..N.intVal:
source &= "echo \""
if i mod 15 == 0:
source &= "FizzBuzz"
elif i mod 3 == 0:
source &= "Fizz"
elif i mod 5 == 0:
source &= "Buzz"
else:
source &= $i
source &= "\"\n"
result = parseStmt(source)
FizzBuzz(100)
Nix
with (import <nixpkgs> { }).lib;
with builtins;
let
fizzbuzz = { x ? 1 }:
''
${if (mod x 15 == 0) then
"FizzBuzz"
else if (mod x 3 == 0) then
"Fizz"
else if (mod x 5 == 0) then
"Buzz"
else
(toString x)}
'' + (if (x < 100) then
fizzbuzz { x = x + 1; } else "");
in
fizzbuzz { }
Oberon-2
MODULE FizzBuzz;
IMPORT Out;
VAR i: INTEGER;
BEGIN
FOR i := 1 TO 100 DO
IF i MOD 15 = 0 THEN
Out.String("FizzBuzz")
ELSIF i MOD 5 = 0 THEN
Out.String("Buzz")
ELSIF i MOD 3 = 0 THEN
Out.String("Fizz")
ELSE
Out.Int(i,0)
END;
Out.Ln
END
END FizzBuzz.
Objeck
bundle Default {
class Fizz {
function : Main(args : String[]) ~ Nil {
for(i := 0; i <= 100; i += 1;) {
if(i % 15 = 0) {
"FizzBuzz"->PrintLine();
}
else if(i % 3 = 0) {
"Fizz"->PrintLine();
}
else if(i % 5 = 0) {
"Buzz"->PrintLine();
}
else {
i->PrintLine();
};
};
}
}
}
Objective-C
// FizzBuzz in Objective-C
#import <Foundation/Foundation.h>
int main(int argc, char* argv[]) {
for (NSInteger i=1; I <= 101; i++) {
if (i % 15 == 0) {
NSLog(@"FizzBuzz\n");
} else if (i % 3 == 0) {
NSLog(@"Fizz\n");
} else if (i % 5 == 0) {
NSLog(@"Buzz\n");
} else {
NSLog(@"%li\n", i);
}
}
}
OCaml
Idiomatic OCaml to solve the stated problem:
let fizzbuzz i =
match i mod 3, i mod 5 with
0, 0 -> "FizzBuzz"
| 0, _ -> "Fizz"
| _, 0 -> "Buzz"
| _ -> string_of_int i
let _ =
for i = 1 to 100 do print_endline (fizzbuzz i) done
With a view toward extensibility, there are many approaches: monadic, list of rules, ... here we'll use a piped sequence of rules to define a new "fizzbuzz" function:
(* Useful rule declaration: "cond => f", 'cond'itionally applies 'f' to 'a'ccumulated value *)
let (=>) cond f a = if cond then f a else a
let append s a = a^s
let fizzbuzz i =
"" |> (i mod 3 = 0 => append "Fizz")
|> (i mod 5 = 0 => append "Buzz")
|> (function "" -> string_of_int i
| s -> s)
Octave
for i = 1:100
if ( mod(i,15) == 0 )
disp("FizzBuzz");
elseif ( mod(i, 3) == 0 )
disp("Fizz")
elseif ( mod(i, 5) == 0 )
disp("Buzz")
else
disp(i)
endif
endfor
Oforth
: fizzbuzz
| i |
100 loop: i [
null
i 3 mod ifZero: [ "Fizz" + ]
i 5 mod ifZero: [ "Buzz" + ]
dup ifNull: [ drop i ] .
] ;
Ol
(for-each (lambda (x)
(print (cond
((and (zero? (mod x 3)) (zero? (mod x 5)))
"FizzBuzz")
((zero? (mod x 3))
"Fizz")
((zero? (mod x 5))
"Buzz")
(else
x))))
(iota 100))
OOC
fizz: func (n: Int) -> Bool {
if(n % 3 == 0) {
printf("Fizz")
return true
}
return false
}
buzz: func (n: Int) -> Bool {
if(n % 5 == 0) {
printf("Buzz")
return true
}
return false
}
main: func {
for(n in 1..100) {
fizz:= fizz(n)
buzz:= buzz(n)
fizz || buzz || printf("%d", n)
println()
}
}
Order
#include <order/interpreter.h>
// Get FB for one number
#define ORDER_PP_DEF_8fizzbuzz ORDER_PP_FN( \
8fn(8N, \
8let((8F, 8fn(8N, 8G, \
8is_0(8remainder(8N, 8G)))), \
8cond((8ap(8F, 8N, 15), 8quote(fizzbuzz)) \
(8ap(8F, 8N, 3), 8quote(fizz)) \
(8ap(8F, 8N, 5), 8quote(buzz)) \
(8else, 8N)))) )
// Print E followed by a comma (composable, 8print is not a function)
#define ORDER_PP_DEF_8print_el ORDER_PP_FN( \
8fn(8E, 8print(8E 8comma)) )
ORDER_PP( // foreach instead of map, to print but return nothing
8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100))
)
Oz
declare
fun {FizzBuzz X}
if X mod 15 == 0 then 'FizzBuzz'
elseif X mod 3 == 0 then 'Fizz'
elseif X mod 5 == 0 then 'Buzz'
else X
end
end
in
for I in 1..100 do
{Show {FizzBuzz I}}
end
PARI/GP
{for(n=1,100,
print(if(n%3,
if(n%5,
n
,
"Buzz"
)
,
if(n%5,
"Fizz"
,
"FizzBuzz"
)
))
)}
Pascal
program fizzbuzz(output);
var
i: integer;
begin
for i := 1 to 100 do
if i mod 15 = 0 then
writeln('FizzBuzz')
else if i mod 3 = 0 then
writeln('Fizz')
else if i mod 5 = 0 then
writeln('Buzz')
else
writeln(i)
end.
PDP-8 Assembly
Runs on SimH, or any PDP-8 with an EAE
/--------------------------------------------------------
/THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL).
/WITH THE FOLLOWING RESTRICTIONS:
/ FOR MULTIPLES OF THREE, PRINT 'FIZZ'
/ FOR MULTIPLES OF FIVE, PRINT 'BUZZ'
/ FOR MULTIPLES OF BOTH THREE AND FIVE, PRINT 'FIZZBUZZ'
/--------------------------------------------------------
/--------------------------------------------------------
/DEFINES
/--------------------------------------------------------
SWBA=7447 /EAE MODE A INSTRUCTION
DVI=7407 /EAE DIVIDE INSTRUCTION
AIX0=0010 /AUTO INDEX REGISTER 0
CR=0215 /CARRIAGE RETURN
LF=0212 /LINEFEED
EOT=0000 /END OF TEXT NUL
FIZMOD=0003 /CONSTANT DECIMAL 3 (FIZZ)
BUZMOD=0005 /CONSTANT DECIMAL 5 (BUZZ)
K10=0012 /CONSTANT DECIMAL 10
LAST=0144 /FIZZBUZZ THE NUMBERS 1..LAST
/0144 OCTAL == 100 DECIMAL
/CAN BE ANY FROM [0001...7777]
/--------------------------------------------------------
/FIZZBUZZ START=0200
/--------------------------------------------------------
*200 /START IN MEMORY AT 0200 OCTAL
FZZBZZ, CLA /CLEAR AC
TAD (-LAST-1 /LOAD CONSTANT -(LAST+1)
DCA CNTR /SET UP MAIN COUNTER
TAD (-FIZMOD /SET UP FIZZ COUNTER
DCA FIZCTR /TO -3
TAD (-BUZMOD /SET UP BUZZ COUNTER
DCA BUZCTR /TO -5
LOOP, ISZ CNTR /READY?
SKP /NO: CONTINUE
JMP I [7600 /YES: RETURN TO OS/8, REPLACE BY
/'HLT' IF NOT ON OS/8
CHKFIZ, ISZ FIZCTR /MULTIPLE OF 3?
JMP CHKBUZ /NO: CONTINUE
TAD FIZSTR /YES: LOAD ADDRESS OF 'FIZZ'
JMS STROUT /PRINT IT TO TTY
TAD (-FIZMOD /RELOAD THE
DCA FIZCTR /MOD 3 COUNTER
CHKBUZ, ISZ BUZCTR /MULTIPLE OF 5?
JMP CHKNUM /NO: CONTINUE
TAD BUZSTR /YES: LOAD ADDRESS OF 'BUZZ'
JMS STROUT /PRINT IT TO TTY
TAD (-BUZMOD /RELOAD THE
DCA BUZCTR /MOD 5 COUNTER
JMP NXTLIN /PRINT NEWLINE AND CONTINUE
CHKNUM, TAD FIZCTR /CHECK WHETHER MOD 3 COUNTER
TAD (FIZMOD /IS RELOADED
SNA /DID WE JUST PRINT 'FIZZ'?
JMP NXTLIN /YES: PRINT NEWLINE AND CONTINUE
CLA /ZERO THE AC
NUM, TAD CNTR /LOAD THE MAIN NUMBER COUNTER
TAD (LAST+1 /OFFSET IT TO A POSITIVE VALUE
JMS NUMOUT /PRINT IT TO THE TTY
NXTLIN, TAD LINSTR /LOAD THE ADDRESS OF THE NEWLINE
JMS STROUT /PRINT IT TO TTY
JMP LOOP /CONTINUE WITH THE NEXT NUMBER
CNTR, 0 /MAIN COUNTER
FIZCTR, 0 /FIZZ COUNTER
BUZCTR, 0 /BUZZ COUNTER
/--------------------------------------------------------
/WRITE ASCII CHARACTER IN AC TO TTY
/PRE : AC=ASCII CHARACTER
/POST: AC=0
/--------------------------------------------------------
CHROUT, .-.
TLS /SEND CHARACTER TO TTY
TSF /IS TTY READY FOR NEXT CHARACTER?
JMP .-1 /NO TRY AGAIN
CLA /AC=0
JMP I CHROUT /RETURN
/--------------------------------------------------------
/WRITE NUL TERMINATED ASCII STRING TO TTY
/PRE : AC=ADDRESS OF STRING MINUS 1
/POST: AC=0
/--------------------------------------------------------
STROUT, .-.
DCA AIX0 /STORE POINTER IN AUTO INDEX 0
STRLOP, TAD I AIX0 /GET NEXT CHARACTER FROM STRING
SNA /SKIP IF NOT EOT
JMP I STROUT /RETURN
JMS CHROUT /PRINT CHARACTER
JMP STRLOP /GO GET NEXT CHARACTER
/--------------------------------------------------------
/WRITE NUMBER IN AC TO TTY AS DECIMAL
/PRE : AC=UNSIGNED NUMBER BETWEEN 0000 AND 7777
/POST: AC=0
/--------------------------------------------------------
NUMOUT, .-.
SWBA /SET EAE IN MODE A
MQL /MQ=NUM; AC=0
TAD BUFFER /LOAD END OF BUFFER
DCA BUFPTR /IN BUFPTR
SKP /NUM IS ALREADY IN MQ
NUMLOP, MQL /MQ=NUM; AC=0
DVI /MQ=NUM/10; AC=NUM-(NUM/10)*10
K10 /DECIMAL 10
TAD ("0 /ADD ASCII ZERO
DCA I BUFPTR /STORE CHAR BUFFER, BACK TO FRONT
CMA /AC=-1
TAD BUFPTR /DECREMENT
DCA BUFPTR /BUFFER POINTER
MQA /MQ -> AC
SZA /READY IF ZERO
JMP NUMLOP /GET NEXT DIGIT
TAD BUFPTR /LOAD START OF CONVERTED NUMBER
JMS STROUT /SEND IT TO TTY
JMP I NUMOUT /RETURN
BUFFER, .+4 /ADDRESS OF BUFFER
*.+4 /RESERVE 4 LOCATIONS (MAX=4095)
EOT /END OF BUFFER
BUFPTR, 0 /POINTER IN BUFFER
/--------------------------------------------------------
/STRINGS
/--------------------------------------------------------
FIZSTR, . /FIZZ STRING
"F; "I; "Z; "Z; EOT
BUZSTR, . /BUZZ STRING
"B; "U; "Z; "Z; EOT
LINSTR, . /NEWLINE STIRNG
CR; LF; EOT
$
Output:
. .PAL FIZBUZ.PA ERRORS DETECTED: 0 LINKS GENERATED: 0 .LOAD FIZBUZ.BN .START 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 .
Peloton
Variable-length padded English dialect
<# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE>
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#>
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#>
<# ONLYFIRSTOFLASTTWO><# SAY LITERAL>Fizz</#></#>
<# ONLYSECONDOFLASTTWO><# SAY LITERAL>Buzz</#></#>
<# BOTH><# SAY LITERAL>FizzBuzz</#></#>
<# NEITHER><# SAY PARAMETER>1</#></#>
</#></#>
<# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#>
Fixed-length English dialect
<@ DEFUDRLIT>__FizzBuzz|<@ SAW>
<@ TSTMD0PARLIT>1|3</@>
<@ TSTMD0PARLIT>1|5</@>
<@ O12><@ SAYLIT>Fizz</@></@>
<@ O22><@ SAYLIT>Buzz</@></@>
<@ BTH><@ SAYLIT>FizzBuzz</@></@>
<@ NTH><@ SAYPAR>1</@></@>
</@></@>
<@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|...</@> </@>
Perl
use strict;
use warnings;
use feature qw(say);
for my $i (1..100) {
say $i % 15 == 0 ? "FizzBuzz"
: $i % 3 == 0 ? "Fizz"
: $i % 5 == 0 ? "Buzz"
: $i;
}
More concisely:
print 'Fizz'x!($_ % 3) . 'Buzz'x!($_ % 5) || $_, "\n" for 1 .. 100;
For code-golfing:
print+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..1e2
For array of values:
map((Fizz)[$_%3].(Buzz)[$_%5]||$_,1..100);
Cheating:
use feature "say";
@a = ("FizzBuzz", 0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz");
say $a[$_ % 15] || $_ for 1..100;
as a subroutine:
sub fizz_buzz {
join("\n", map {
sub mult {$_ % shift == 0};
my @out;
if (mult 3) { push @out, "Fizz"; }
if (mult 5) { push @out, "Buzz"; }
if (!@out) {push @out, $_; }
join('', @out);
} (1..100))."\n";
}
print fizz_buzz;
By transforming a list:
@FB1 = (1..100);
@FB2 = map{!($_%3 or $_%5)?'FizzBuzz': $_}@FB1;
@FB3 = map{(/\d/ and !($_%3))?'Fizz': $_}@FB2;
@FB4 = map{(/\d/ and !($_%5))?'Buzz': $_}@FB3;
@FB5 = map{$_."\n"}@FB4;
print @FB5;
Phix
constant x = {"%d\n","Fizz\n","Buzz\n","FizzBuzz\n"} for i=1 to 100 do printf(1,x[1+(remainder(i,3)=0)+2*(remainder(i,5)=0)],i) end for
Two variants with tabulated output:
function f(integer i) integer idx = 1+(remainder(i,3)=0)+2*(remainder(i,5)=0) return sprintf({"%-8d","Fizz ","Buzz ","FizzBuzz"}[idx],i) end function printf(1,join_by(apply(tagset(100),f),10,10))
(output same as below)
sequence s = apply(true,sprintf,{{"%-8d"},tagset(100)}) for i=3 to 100 by 3 do s[i] = "Fizz " end for for i=5 to 100 by 5 do s[i] = "Buzz " end for for i=15 to 100 by 15 do s[i] = "FizzBuzz" end for printf(1,join_by(s,10,10))
- Output:
1 11 Fizz 31 41 Fizz 61 71 Fizz 91 2 Fizz 22 32 Fizz 52 62 Fizz 82 92 Fizz 13 23 Fizz 43 53 Fizz 73 83 Fizz 4 14 Fizz 34 44 Fizz 64 74 Fizz 94 Buzz FizzBuzz Buzz Buzz FizzBuzz Buzz Buzz FizzBuzz Buzz Buzz Fizz 16 26 Fizz 46 56 Fizz 76 86 Fizz 7 17 Fizz 37 47 Fizz 67 77 Fizz 97 8 Fizz 28 38 Fizz 58 68 Fizz 88 98 Fizz 19 29 Fizz 49 59 Fizz 79 89 Fizz Buzz Buzz FizzBuzz Buzz Buzz FizzBuzz Buzz Buzz FizzBuzz Buzz
Grotesquely inefficient (non-tabulated output), just for fun. Can you do worse, yet keep it semi-plausibile that someone might have actually earnestly written it?
constant threes = tagset(100,0,3), fives = tagset(100,0,5), fifteens = tagset(100,0,15) for i=1 to 100 do if not find(i,threes) and not find(i,fives) and not find(i,fifteens) then printf(1,"%d",i) end if if find(i,threes) and not find(i,fives) and not find(i,fifteens) then printf(1,"Fizz") end if if not find(i,threes) and find(i,fives) and not find(i,fifteens) then printf(1,"Buzz",i) end if if find(i,threes) and find(i,fives) and find(i,fifteens) then printf(1,"FizzBuzz") end if printf(1,"\n") end for
PHL
module fizzbuzz;
extern printf;
@Integer main [
var i = 1;
while (i <= 100) {
if (i % 15 == 0)
printf("FizzBuzz");
else if (i % 3 == 0)
printf("Fizz");
else if (i % 5 == 0)
printf("Buzz");
else
printf("%d", i);
printf("\n");
i = i::inc;
}
return 0;
]
PHP
if/else ladder approach
<?php
for ($i = 1; $i <= 100; $i++)
{
if (!($i % 15))
echo "FizzBuzz\n";
else if (!($i % 3))
echo "Fizz\n";
else if (!($i % 5))
echo "Buzz\n";
else
echo "$i\n";
}
?>
Concatenation approach
Uses PHP's concatenation operator (.=) to build the output string. The concatenation operator allows us to add data to the end of a string without overwriting the whole string. Since Buzz will always appear if our number is divisible by five, and Buzz is the second part of "FizzBuzz", we can simply append "Buzz" to our string.
In contrast to the if-else ladder, this method lets us skip the check to see if $i is divisible by both 3 and 5 (i.e. 15). However, we get the added complexity of needing to reset $str to an empty string (not necessary in some other languages), and we also need a separate if statement to check to see if our string is empty, so we know if $i was not divisible by 3 or 5.
<?php
for ( $i = 1; $i <= 100; ++$i )
{
$str = "";
if (!($i % 3 ) )
$str .= "Fizz";
if (!($i % 5 ) )
$str .= "Buzz";
if ( empty( $str ) )
$str = $i;
echo $str . "\n";
}
?>
Concatenation approach without if-s
<?php
for (
$i = 0;
$i++ < 100;
$o = ($i % 3 ? '' : 'Fizz') . ($i % 5 ? '' : 'Buzz')
)
echo $o ? : $i, PHP_EOL;
?>
One Liner Approach
<?php
for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i);
?>
Compact One Liner Approach
for($i=0;$i++<100;)echo($i%3?'':'Fizz').($i%5?'':'Buzz')?:$i,"\n";
Array One Liner Approach
for($i = 0; $i++ < 100;) echo [$i, 'Fizz', 'Buzz', 'FizzBuzz'][!($i % 3) + 2 * !($i % 5)], "\n";
Picat
Picat supports different programming styles/paradigms.
First some "standalone" predicates.
Using a map
fizzbuzz_map =>
println(fizzbuzz_map),
FB = [I : I in 1..100],
Map = [(3="Fizz"),(5="Buzz"),(15="FizzBuzz")],
foreach(I in FB, K=V in Map)
if I mod K == 0 then
FB[I] := V
end
end,
println(FB).
Using a template for the pattern
fizzbuzz_template1 =>
println(fizzbuzz_template1),
N = 100,
F = [_,_,fizz,_,buzz,fizz,_,_,fizz,buzz,_,fizz,_,_,fizzbuzz],
FF = [F : _I in 1..1+N div F.length].flatten(),
foreach(I in 1..N)
(var(FF[I]) -> print(I) ; print(FF[I])),
print(" ")
end,
nl.
Another version with templates
fizzbuzz_template2 =>
println(fizzbuzz_template2),
N = 100,
F = new_list(N),
FV = [3,5,15],
FN = ["Fizz","Buzz","FizzBuzz"],
foreach(I in 1..N, {Val,Name} in zip(FV,FN))
if I mod Val == 0 then F[I] := Name end
end,
foreach(I in 1..N)
printf("%w ", cond(var(F[I]),I, F[I]))
end,
nl.
Below are some versions for identifying the FizzBuzziness of a number.
To be used with the following general wrapper:
fizzbuzz(Goal) =>
println(Goal),
foreach(I in 1..100)
printf("%w ", apply(Goal,I))
end,
nl.
Plain imperative approach: if/else
fb1(I) = V =>
V = I.to_string(),
if I mod 15 == 0 then V := "FizzBuzz"
elseif I mod 3 == 0 then V := "Fizz"
elseif I mod 5 == 0 then V := "Buzz"
end.
Pattern matching + conditions in head
fb2(I) = "FizzBuzz", I mod 15 == 0 => true.
fb2(I) = "Fizz", I mod 3 == 0 => true.
fb2(I) = "Buzz", I mod 5 == 0 => true.
fb2(I) = I.to_string() => true.
Another pattern matching approach
fb3(I) = fb3b(I, I mod 3, I mod 5).
fb3b(_I,0,0) = "FizzBuzz".
fb3b(_I,_,0) = "Buzz".
fb3b(_I,0,_) = "Fizz".
fb3b(I,_,_) = I.
Using cond/3 and string concatenation
fb4(I) = cond(I mod 3 == 0, "Fizz", "") ++
cond(I mod 5 == 0, "Buzz", "") ++
cond(not ((I mod 3 == 0; I mod 5==0)), I.to_string(), "").
Recursive function (conditions in head)
fizzbuzz_rec =>
print(fizzbuzz_rec),
fb5(100,[],L),
println(L).
fb5(N,L1,L), N = 0 ?=>
L = L1.reverse().
fb5(N,L1,L),N mod 15 == 0 ?=>
fb5(N-1,L1 ++ ["FizzBuzz"], L).
fb5(N,L1,L), N mod 5 == 0 ?=>
fb5(N-1,L1 ++ ["Buzz"], L).
fb5(N,L1,L), N mod 3 == 0 ?=>
fb5(N-1,L1 ++ ["Fizz"], L).
fb5(N,L1,L), N mod 3 > 0, N mod 5 > 0 =>
fb5(N-1,L1 ++ [N.to_string()], L).
Golfing style
fizzbuzz_golf =>
println(fizzbuzz_golf),
[cond(P=="",I,P):I in 1..100,(I mod 3==0->P="Fizz";P=""),(I mod 5==0->P:=P++"Buzz";true)].println().
Planner version
Picat has support for "classic" planning problems. The planner
module must be imported.
import planner.
fizzbuzz_planner =>
println(fizzbuzz_planner),
plan(100,Plan),
println(Plan.reverse()),
nl.
final(Goal) => Goal == 0.
action(H,To,Move,Cost) ?=>
H mod 15 == 0,
Move = "FizzBuzz",
To = H-1,
Cost = 1.
action(H,To,Move,Cost) ?=>
H mod 5 == 0,
Move = "Buzz",
To = H-1,
Cost = 1.
action(H,To,Move,Cost) ?=>
H mod 3 == 0,
Move = "Fizz",
To = H-1,
Cost = 1.
action(H,To,Move,Cost) =>
H mod 3 > 0,
H mod 5 > 0,
Move = H.to_string(),
To = H-1,
Cost = 1.
Here we test everything.
go =>
fizzbuzz_map,
fizzbuzz_template1,
fizzbuzz_template2,
fizzbuzz_planner,
fizzbuzz_rec,
fizzbuzz_golf,
FBs = [fb1,fb2,fb3,fb4],
foreach(FB in FBs)
call(fizzbuzz,FB)
end,
nl.
PicoLisp
We could simply use 'at' here:
(for N 100
(prinl
(or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) )
# Above, we simply count till 100 'prin'-ting number 'at' 3rd ('Fizz'), 5th ('Buzz') and 'pack'-ing 15th number ('FizzBuzz').
# Rest of the times 'N' is printed as it loops in 'for'.
Or do it the standard way:
(for N 100
(prinl
(cond
((=0 (% N 15)) "FizzBuzz")
((=0 (% N 3)) "Fizz")
((=0 (% N 5)) "Buzz")
(T N) ) ) )
Pike
int main(){
for(int i = 1; i <= 100; i++) {
if(i % 15 == 0) {
write("FizzBuzz\n");
} else if(i % 3 == 0) {
write("Fizz\n");
} else if(i % 5 == 0) {
write("Buzz\n");
} else {
write(i + "\n");
}
}
}
PILOT
C :i = 0
*loop
C :i = i + 1
J ( i > 100 ) : *finished
C :modulo = i % 15
J ( modulo = 0 ) : *fizzbuzz
C :modulo = i % 3
J ( modulo = 0 ) : *fizz
C :modulo = i % 5
J ( modulo = 0 ) : *buzz
T :#i
J : *loop
*fizzbuzz
T :FizzBuzz
J : *loop
*fizz
T :Fizz
J : *loop
*buzz
T :Buzz
J : *loop
*finished
END:
PIR
.sub main :main
.local int f
.local int mf
.local int skipnum
f = 1
LOOP:
if f > 100 goto DONE
skipnum = 0
mf = f % 3
if mf == 0 goto FIZZ
FIZZRET:
mf = f % 5
if mf == 0 goto BUZZ
BUZZRET:
if skipnum > 0 goto SKIPNUM
print f
SKIPNUM:
print "\n"
inc f
goto LOOP
end
FIZZ:
print "Fizz"
inc skipnum
goto FIZZRET
end
BUZZ:
print "Buzz"
inc skipnum
goto BUZZRET
end
DONE:
end
.end
PL/I
do i = 1 to 100;
select;
when (mod(i,15) = 0) put skip list ('FizzBuzz');
when (mod(i,3) = 0) put skip list ('Fizz');
when (mod(i,5) = 0) put skip list ('Buzz');
otherwise put skip list (i);
end;
end;
PL/M
100H:
/* DECLARE OUTPUT IN TERMS OF CP/M -
PL/M DOES NOT COME WITH ANY STANDARD LIBRARY */
BDOS: PROCEDURE(FUNC, ARG);
DECLARE FUNC BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PUT$STRING: PROCEDURE(STR);
DECLARE STR ADDRESS;
CALL BDOS(9, STR);
CALL BDOS(9, .(13,10,'$'));
END PUT$STRING;
/* PRINT A NUMBER */
PUT$NUMBER: PROCEDURE(N);
DECLARE S (5) BYTE INITIAL ('...$');
DECLARE P ADDRESS;
DECLARE (N, D, C BASED P) BYTE;
P = .S(3);
DIGIT:
P = P-1;
C = (N MOD 10) + '0';
N = N/10;
IF N > 0 THEN GO TO DIGIT;
CALL PUT$STRING(P);
END PUT$NUMBER;
/* FIZZBUZZ */
DECLARE N BYTE;
DO N = 1 TO 100;
IF N MOD 15 = 0 THEN
CALL PUT$STRING(.'FIZZBUZZ$');
ELSE IF N MOD 5 = 0 THEN
CALL PUT$STRING(.'BUZZ$');
ELSE IF N MOD 3 = 0 THEN
CALL PUT$STRING(.'FIZZ$');
ELSE
CALL PUT$NUMBER(N);
END;
/* EXIT TO CP/M */
CALL BDOS(0,0);
EOF
PL/SQL
begin
for i in 1 .. 100
loop
case
when mod(i, 15) = 0 then
dbms_output.put_line('FizzBuzz');
when mod(i, 5) = 0 then
dbms_output.put_line('Buzz');
when mod(i, 3) = 0 then
dbms_output.put_line('Fizz');
else
dbms_output.put_line(i);
end case;
end loop;
end;
Pony
use "collections"
actor Main
new create(env: Env) =>
for i in Range[I32](1, 100) do
env.out.print(fizzbuzz(i))
end
fun fizzbuzz(n: I32): String =>
if (n % 15) == 0 then
"FizzBuzz"
elseif (n % 5) == 0 then
"Buzz"
elseif (n % 3) == 0 then
"Fizz"
else
n.string()
end
Pop11
lvars str;
for i from 1 to 100 do
if i rem 15 = 0 then
'FizzBuzz' -> str;
elseif i rem 3 = 0 then
'Fizz' -> str;
elseif i rem 5 = 0 then
'Buzz' -> str;
else
'' >< i -> str;
endif;
printf(str, '%s\n');
endfor;
PostScript
1 1 100 {
/c false def
dup 3 mod 0 eq { (Fizz) print /c true def } if
dup 5 mod 0 eq { (Buzz) print /c true def } if
c {pop}{( ) cvs print} ifelse
(\n) print
} for
or...
/fizzdict 100 dict def
fizzdict begin
/notmod{ ( ) cvs } def
/mod15 { dup 15 mod 0 eq { (FizzBuzz)def }{pop}ifelse} def
/mod3 { dup 3 mod 0 eq {(Fizz)def}{pop}ifelse} def
/mod5 { dup 5 mod 0 eq {(Buzz)def}{pop}ifelse} def
1 1 100 { mod3 } for
1 1 100 { mod5 } for
1 1 100 { mod15} for
1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for
end
Potion
1 to 100 (a):
if (a % 15 == 0):
'FizzBuzz'.
elsif (a % 3 == 0):
'Fizz'.
elsif (a % 5 == 0):
'Buzz'.
else: a. string print
"\n" print.
PowerShell
Straightforward, looping
for ($i = 1; $i -le 100; $i++) {
if ($i % 15 -eq 0) {
"FizzBuzz"
} elseif ($i % 5 -eq 0) {
"Buzz"
} elseif ($i % 3 -eq 0) {
"Fizz"
} else {
$i
}
}
Pipeline, Switch
$txt=$null
1..100 | ForEach-Object {
switch ($_) {
{ $_ % 3 -eq 0 } { $txt+="Fizz" }
{ $_ % 5 -eq 0 } { $txt+="Buzz" }
$_ { if($txt) { $txt } else { $_ }; $txt=$null }
}
}
Concatenation
1..100 | ForEach-Object {
$s = ''
if ($_ % 3 -eq 0) { $s += "Fizz" }
if ($_ % 5 -eq 0) { $s += "Buzz" }
if (-not $s) { $s = $_ }
$s
}
Piping, Evaluation, Concatenation
1..100 | % {write-host("$(if(($_ % 3 -ne 0) -and ($_ % 5 -ne 0)){$_})$(if($_ % 3 -eq 0){"Fizz"})$(if($_ % 5 -eq 0){"Buzz"})")}
Filter, Piping, Regex Matching, Array Auto-Selection
filter fizz-buzz{
@(
$_,
"Fizz",
"Buzz",
"FizzBuzz"
)[
2 *
($_ -match '[05]$') +
($_ -match '(^([369][0369]?|[258][147]|[147][258]))$')
]
}
1..100 | fizz-buzz
String Manipulation with Regex
(1..100 -join "`n") + "`nFizzBuzz" -replace '(?ms)(^([369]([369]|(?=0|$))|[258][147]|[147]([28]|(?=5))))(?=[05]?$.*(Fizz))|(((?<=[369])|[^369])0+|((?<=[147\s])|[^147\s])5)(?=$.*(Buzz))|FizzBuzz', '$5$9'
Processing
Console & Visualization
Reserved variable "width" in Processing is 100 pixels by default, suitable for this FizzBuzz exercise. Accordingly, range is pixel index from 0 to 99.
for (int i = 0; i < width; i++) {
if (i % 3 == 0 && i % 5 == 0) {
stroke(255, 255, 0);
println("FizzBuzz!");
}
else if (i % 5 == 0) {
stroke(0, 255, 0);
println("Buzz");
}
else if (i % 3 == 0) {
stroke(255, 0, 0);
println("Fizz");
}
else {
stroke(0, 0, 255);
println(i);
}
line(i, 0, i, height);
}
Console & Visualization, Ternary
for (int i = 0; i < width; i++) {
stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF);
line(i, 0, i, height);
println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i);
}
Console
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) {
print("Fizz");
}
if (i % 5 == 0) {
print("Buzz");
}
if (i % 3 != 0 && i % 5 != 0) {
print(i);
}
print("\n");
}
Console, "Futureproof"
for(int i = 1; i <= 100; i++){
String output = "";
if(i % 3 == 0) output += "Fizz";
if(i % 5 == 0) output += "Buzz";
// copy & paste above line to add more tests
if(output == "") output = str(i);
println(output);
}
All examples produce the same console output:
- Output:
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
Prolog
Maybe not the most conventional way to write this in Prolog. The fizzbuzz predicate uses a higher-order predicate and print_item uses the if-then-else construction.
fizzbuzz :-
foreach(between(1, 100, X), print_item(X)).
print_item(X) :-
( 0 is X mod 15
-> print('FizzBuzz')
; 0 is X mod 3
-> print('Fizz')
; 0 is X mod 5
-> print('Buzz')
; print(X)
),
nl.
More conventional:
fizzbuzz(X) :- 0 is X mod 15, write('FizzBuzz').
fizzbuzz(X) :- 0 is X mod 3, write('Fizz').
fizzbuzz(X) :- 0 is X mod 5, write('Buzz').
fizzbuzz(X) :- write(X).
dofizzbuzz :- foreach(between(1, 100, X), (fizzbuzz(X),nl)).
Clearer:
% N /3? /5? V
fizzbuzz(_, yes, yes, 'FizzBuzz').
fizzbuzz(_, yes, no, 'Fizz').
fizzbuzz(_, no, yes, 'Buzz').
fizzbuzz(N, no, no, N).
% Unifies V with 'yes' if D divides evenly into N, 'no' otherwise.
divisible_by(N, D, V) :-
( 0 is N mod D -> V = yes
; V = no).
% Print 'Fizz', 'Buzz', 'FizzBuzz' or N as appropriate.
fizz_buzz_or_n(N) :-
divisible_by(N, 3, Fizz),
divisible_by(N, 5, Buzz),
fizzbuzz(N, Fizz, Buzz, FB),
format("~p -> ~p~n", [N, FB]).
main :-
foreach(between(1,100, N), fizz_buzz_or_n(N)).
Using modern Prolog techniques, resulting in idiomatic, highly declarative code:
% This implementation uses modern Prolog techniques
% in order to be an idiomatic solution that uses logical purity, generality and determinism wherever possible:
% - CLP(Z): constraint logic programming on integers.
% - library(reif): efficient logical predicates based on 'Indexing dif/2'.
:- module(fizz_buzz, [main/0, integer_fizzbuzz_below_100/2, integer_fizzbuzz/2]).
:- use_module(library(reif)).
% for Scryer-Prolog:
:- use_module(library(clpz)).
:- use_module(library(between)).
:- use_module(library(iso_ext)).
:- use_module(library(si)).
% for SWI-Prolog:
% :- use_module(library(clpfd)).
% Prints all solutions to `integer_fizzbuzz_below_100` each on a separate line, in order.
% Logically-impure shell, as currently there is no logically-pure way to write to a filestream.
main :-
forall(integer_fizzbuzz_below_100(_, FizzBuzz), write_line(FizzBuzz)).
write_line(Value) :-
write(Value),
nl.
% Constrains FizzBuzz results to the range 1 <= X <= 100,
% and (for the 'most general query' where neither X or FizzBuzz is concrete)
% ensures results are traversed in order low -> high X.
%
% ?- integer_fizzbuzz_below_100(X, FizzBuzz) % generate all the results in order
% ?- integer_fizzbuzz_below_100(27, Result) % Find out what output `27` will produce (it's 'Fizz'.)
% ?- integer_fizzbuzz_below_100(X, 'Fizz') % generate all the numbers which would print 'Fizz' in order (3, 6, 9, etc).
% ?- integer_fizzbuzz_below_100(X, Res), integer_si(Res) % generate all the numbers which would print themselves in order (1, 2, 4, 6, 7, 8, 11, etc).
% ?- integer_fizzbuzz_below_100(X, Res), is_of_type(integer, Res) % SWI-Prolog version doing the same.
integer_fizzbuzz_below_100(X, FizzBuzz) :-
between(1, 100, X),
integer_fizzbuzz(X, FizzBuzz).
% States the relationship between a number
% and its FizzBuzz representation.
%
% Because constraints are propagated lazily,
% prompting this predicate without having constrained `Num`
% to a particular integer value will give you its definition back.
% Put differently: This predicate returns the whole solution space at once,
% and external labeling techniques are required to traverse and concretize this solution space
% in an order that we like.
integer_fizzbuzz(Num, FizzBuzz) :-
if_(Num mod 15 #= 0, FizzBuzz = 'FizzBuzz',
if_(Num mod 5 #= 0, FizzBuzz = 'Buzz',
if_(Num mod 3 #= 0, FizzBuzz = 'Fizz',
Num = FizzBuzz)
)
).
% Reifiable `#=`.
#=(X, Y, T) :-
X #= X1,
Y #= Y1,
zcompare(C, X1, Y1),
eq_t(C, T).
eq_t(=, true).
eq_t(<, false).
eq_t(>, false).
PureBasic
See FizzBuzz/Basic
Pyret
fun fizzbuzz(n :: NumPositive) -> String:
doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'.
For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.```
ask:
| num-modulo(n, 15) == 0 then: "FizzBuzz"
| num-modulo(n, 3) == 0 then: "Fizz"
| num-modulo(n, 5) == 0 then: "Buzz"
| otherwise: num-to-string(n)
end
where:
fizzbuzz(1) is "1"
fizzbuzz(101) is "101"
fizzbuzz(45) is "FizzBuzz"
fizzbuzz(33) is "Fizz"
fizzbuzz(25) is "Buzz"
end
range(1, 101).map(fizzbuzz).each(print)
Python
Python2: Simple
for i in xrange(1, 101):
if i % 15 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print i
Python3: Simple
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Python: Simple - no duplication
for n in range(1,101):
response = ''
if not n%3:
response += 'Fizz'
if not n%5:
response += 'Buzz'
print(response or n)
One liner using string concatenation:
for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i)
One liner another code:
for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)
List Comprehensions:
for n in range(1, 100):
fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ])
print fb if fb else n
Another list comprehension:
print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)]))
Python: List Comprehension (Python 3)
[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)]
Python: Lazily
You can also create a lazy, unbounded sequence by using generator expressions:
from itertools import cycle, izip, count, islice
fizzes = cycle([""] * 2 + ["Fizz"])
buzzes = cycle([""] * 4 + ["Buzz"])
both = (f + b for f, b in izip(fizzes, buzzes))
# if the string is "", yield the number
# otherwise yield the string
fizzbuzz = (word or n for word, n in izip(both, count(1)))
# print the first 100
for i in islice(fizzbuzz, 100):
print i
Or equivalently, in terms of map, and Python 3 libraries:
'''Fizz buzz'''
from itertools import count, cycle, islice
# fizzBuzz :: () -> Generator [String]
def fizzBuzz():
'''A non-finite stream of fizzbuzz terms.
'''
return map(
lambda f, b, n: (f + b) or str(n),
cycle([''] * 2 + ['Fizz']),
cycle([''] * 4 + ['Buzz']),
count(1)
)
# ------------------------- TEST -------------------------
def main():
'''Display of first 100 terms of the fizzbuzz series.
'''
print(
'\n'.join(
list(islice(
fizzBuzz(),
100
))
)
)
if __name__ == '__main__':
main()
Python3.8: With walrus operator
print(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i := n**4%-15) > -14 else n, range(1,100)))
Python: Math tricks
Numbers ending in 5 or 0 are divisible by 5. Numbers whose digits recursively summed to a single-digit number == 3,6 or 9 are divisible by 3.
def numsum(n):
''' The recursive sum of all digits in a number
unit a single character is obtained'''
res = sum([int(i) for i in str(n)])
if res < 10: return res
else : return numsum(res)
for n in range(1,101):
response = 'Fizz'*(numsum(n) in [3,6,9]) + \
'Buzz'*(str(n)[-1] in ['5','0'])\
or n
print(response)
Python3: Super concise: 1 line
print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101)))
Q
q){(sum 1 2*0=x mod/:3 5)'[`$string x;`fizz;`buzz;`fizzbuzz]}1+til 20
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz
https://code.kx.com/q/learn/reading/fizzbuzz/
QB64
For n = 1 To 100
If n Mod 15 = 0 Then
Print "FizzBuzz"
ElseIf n Mod 5 = 0 Then
Print "Buzz"
ElseIf n Mod 3 = 0 Then
Print "Fizz"
Else
Print n
End If
Next
Quackery
[ times
[ i^ 1+
' echo
over 3 mod 0 = if
[ say "Fizz"
drop ' drop ]
over 5 mod 0 = if
[ say "Buzz"
drop ' drop ]
do
sp ]
cr ] is fizzbuzz ( n --> )
say 'First 100 turns in the game of fizzbuzz:' cr cr
100 fizzbuzz cr
R
xx <- x <- 1:100
xx[x %% 3 == 0] <- "Fizz"
xx[x %% 5 == 0] <- "Buzz"
xx[x %% 15 == 0] <- "FizzBuzz"
xx
Or, without directly checking for divisibility by 15:
xx <- rep("", 100)
x <- 1:100
xx[x %% 3 == 0] <- paste0(xx[x %% 3 == 0], "Fizz")
xx[x %% 5 == 0] <- paste0(xx[x %% 5 == 0], "Buzz")
xx[xx == ""] <- x[xx == ""]
xx
Or, (ab)using the vector recycling rule:
x <- paste0(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz"))
cat(ifelse(x == "", 1:100, x), sep = "\n")
Or, for an abuse of the recycling rules that could be generalised:
x <- paste0(rep("", 100), rep(c("", "Fizz"), times = c(2, 1)), rep(c("", "Buzz"), times = c(4, 1)))
cat(ifelse(x == "", 1:100, x), sep = "\n")
Or, with a more straightforward use of ifelse:
x <- 1:100
ifelse(x %% 15 == 0, 'FizzBuzz',
ifelse(x %% 5 == 0, 'Buzz',
ifelse(x %% 3 == 0, 'Fizz', x)))
Or, adapting from General FizzBuzz#Names solution:
namedNums <- c(Fizz = 3, Buzz = 5)
for(i in 1:100)
{
isFactor <- i %% namedNums == 0
print(if(any(isFactor)) paste0(names(namedNums)[isFactor], collapse = "") else i)
}
Racket
#lang racket
(for ([n (in-range 1 101)])
(displayln
(match (gcd n 15)
[15 "fizzbuzz"]
[3 "fizz"]
[5 "buzz"]
[_ n])))
Raku
(formerly Perl 6)
Most straightforwardly:
for 1 .. 100 {
when $_ %% (3 & 5) { say 'FizzBuzz'; }
when $_ %% 3 { say 'Fizz'; }
when $_ %% 5 { say 'Buzz'; }
default { .say; }
}
Or abusing multi subs:
multi sub fizzbuzz(Int $ where * %% 15) { 'FizzBuzz' }
multi sub fizzbuzz(Int $ where * %% 5) { 'Buzz' }
multi sub fizzbuzz(Int $ where * %% 3) { 'Fizz' }
multi sub fizzbuzz(Int $number ) { $number }
(1 .. 100)».&fizzbuzz.say;
Or abusing list metaoperators:
[1..100].map({[~] ($_%%3, $_%%5) »||» "" Z&& <fizz buzz> or $_ })».say
Concisely (readable):
say 'Fizz' x $_ %% 3 ~ 'Buzz' x $_ %% 5 || $_ for 1 .. 100;
Shortest FizzBuzz to date:
say "Fizz"x$_%%3~"Buzz"x$_%%5||$_ for 1..100
And here's an implementation that never checks for divisibility:
.say for
(
(flat ('' xx 2, 'Fizz') xx *)
Z~
(flat ('' xx 4, 'Buzz') xx *)
)
Z||
1 .. 100;
RapidQ
The BASIC solutions work with RapidQ, too. However, here is a bit more esoteric solution using the IIF() function.
FOR i=1 TO 100
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
PRINT IIF(LEN(t$), t$, i)
NEXT i
Rascal
import IO;
public void fizzbuzz() {
for(int n <- [1 .. 100]){
fb = ((n % 3 == 0) ? "Fizz" : "") + ((n % 5 == 0) ? "Buzz" : "");
println((fb == "") ?"<n>" : fb);
}
}
Raven
100 each 1 + as n
''
n 3 mod 0 = if 'Fizz' cat
n 5 mod 0 = if 'Buzz' cat
dup empty if drop n
say
REALbasic
See FizzBuzz/Basic
ReasonML
let fizzbuzz i =>
switch (i mod 3, i mod 5) {
| (0, 0) => "FizzBuzz"
| (0, _) => "Fizz"
| (_, 0) => "Buzz"
| _ => string_of_int i
};
for i in 1 to 100 {
print_endline (fizzbuzz i)
};
REBOL
An implementation that concatenates strings and includes a proper code header (title, date, etc.)
REBOL [
Title: "FizzBuzz"
URL: http://rosettacode.org/wiki/FizzBuzz
]
; Concatenative. Note use of 'case/all' construct to evaluate all
; conditions. I use 'copy' to allocate a new string each time through
; the loop -- otherwise 'x' would get very long...
repeat i 100 [
x: copy ""
case/all [
0 = mod i 3 [append x "Fizz"]
0 = mod i 5 [append x "Buzz"]
"" = x [x: mold i]
]
print x
]
Here is an example by Nick Antonaccio.
repeat i 100 [
print switch/default 0 compose [
(mod i 15) ["fizzbuzz"]
(mod i 3) ["fizz"]
(mod i 5) ["buzz"]
][i]
]
And a minimized version:
repeat i 100[j:""if i // 3 = 0[j:"fizz"]if i // 5 = 0[j: join j"buzz"]if""= j[j: i]print j]
The following is presented as a curiosity only, not as an example of good coding practice:
m: func [i d] [0 = mod i d]
spick: func [t x y][either any [not t "" = t][y][x]]
zz: func [i] [rejoin [spick m i 3 "Fizz" "" spick m i 5 "Buzz" ""]]
repeat i 100 [print spick z: zz i z i]
Red
Red ["FizzBuzz"]
repeat i 100 [
print case [
i % 15 = 0 ["FizzBuzz"]
i % 5 = 0 ["Buzz"]
i % 3 = 0 ["Fizz"]
true [i]
]
]
Retro
This is a port of some Forth code.
: fizz? ( s-f ) 3 mod 0 = ;
: buzz? ( s-f ) 5 mod 0 = ;
: num? ( s-f ) dup fizz? swap buzz? or 0 = ;
: ?fizz ( s- ) fizz? [ "Fizz" puts ] ifTrue ;
: ?buzz ( s- ) buzz? [ "Buzz" puts ] ifTrue ;
: ?num ( s- ) num? &putn &drop if ;
: fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ;
: all ( - ) 100 [ 1+ fizzbuzz ] iter ;
It's cleaner to use quotes and combinators though:
needs math'
: <fizzbuzz>
[ 15 ^math'divisor? ] [ drop "FizzBuzz" puts ] when
[ 3 ^math'divisor? ] [ drop "Fizz" puts ] when
[ 5 ^math'divisor? ] [ drop "Buzz" puts ] when putn ;
: fizzbuzz cr 100 [ 1+ <fizzbuzz> space ] iter ;
REXX
This version's program logic closely mirrors the problem statement:
three IF-THEN
/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/*╔═══════════════════════════════════╗*/
do j=1 to 100; z= j /*║ ║*/
if j//3 ==0 then z= 'Fizz' /*║ The divisors (//) of the IFs ║*/
if j//5 ==0 then z= 'Buzz' /*║ must be in ascending order. ║*/
if j//(3*5)==0 then z= 'FizzBuzz' /*║ ║*/
say right(z, 8) /*╚═══════════════════════════════════╝*/
end /*j*/ /*stick a fork in it, we're all done. */
output
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
SELECT-WHEN
This version is a different form, but essentially identical to the IF-THEN (above),
but doesn't require the use of a temporary variable to hold/contain the output.
/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/*╔═══════════════════════════════════╗*/
do j=1 to 100 /*║ ║*/
select /*║ ║*/
when j//15==0 then say 'FizzBuzz' /*║ The divisors (//) of the WHENs ║*/
when j//5 ==0 then say ' Buzz' /*║ must be in descending order. ║*/
when j//3 ==0 then say ' Fizz' /*║ ║*/
otherwise say right(j, 8) /*╚═══════════════════════════════════╝*/
end /*select*/
end /*j*/ /*stick a fork in it, we're all done. */
output is identical to the 1st REXX version.
two IF-THEN
This version lends itself to expansion (such as using Jazz for multiples of 7).
/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
do j=1 for 100; _=
if j//3 ==0 then _=_'Fizz'
if j//5 ==0 then _=_'Buzz'
/* if j//7 ==0 then _=_'Jazz' */ /* ◄─── note that this is a comment. */
say right(word(_ j,1),8)
end /*j*/ /*stick a fork in it, we're all done. */
output is identical to the 1st REXX version.
"geek" version
/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/* [↓] concise, but somewhat obtuse. */
do j=1 for 100
say right(word(word('Fizz', 1+(j//3\==0))word('Buzz', 1+(j//5\==0)) j, 1), 8)
end /*j*/
/*stick a fork in it, we're all done. */
output is identical to the 1st REXX version.
Ring
for n = 1 to 100
if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl
but n % 5 = 0 see "" + n + " = " + "Buzz" + nl
but n % 3 = 0 see "" + n + " = " + "Fizz" + nl
else see "" + n + " = " + n + nl ok
next
Robotic
set "local1" to 1
: "loop"
wait for 10
if "('local1' % 15)" = 0 then "fizzbuzz"
if "('local1' % 3)" = 0 then "fizz"
if "('local1' % 5)" = 0 then "buzz"
* "&local1&"
: "inc"
inc "local1" by 1
if "local1" <= 100 then "loop"
goto "done"
: "fizzbuzz"
* "FizzBuzz"
goto "inc"
: "fizz"
* "Fizz"
goto "inc"
: "buzz"
* "Buzz"
goto "inc"
: "done"
end
The wait for 10 function is not really necessary, but it helps to slow down the output.
Rockstar
Midnight takes your heart and your soul While your heart is as high as your soul Put your heart without your soul into your heart Give back your heart Desire is a lovestruck ladykiller My world is nothing Fire is ice Hate is water Until my world is Desire, Build my world up If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing Shout "FizzBuzz!" Take it to the top If Midnight taking my world, Fire is nothing Shout "Fizz!" Take it to the top If Midnight taking my world, Hate is nothing Say "Buzz!" Take it to the top Whisper my world
Ruby
1.upto(100) do |n|
print "Fizz" if a = (n % 3).zero?
print "Buzz" if b = (n % 5).zero?
print n unless (a || b)
puts
end
A bit more straightforward:
(1..100).each do |n|
puts if (n % 15).zero?
"FizzBuzz"
elsif (n % 5).zero?
"Buzz"
elsif (n % 3).zero?
"Fizz"
else
n
end
end
Enumerable#Lazy and classes:
We can grab the first n fizz/buzz/fizzbuzz numbers in a list with a user defined function (filter_map), starting at the number we desire
i.e, grabbing the first 10 fizz numbers starting from 30, fizz = Fizz.new(30,10) #=> [30, 33, 36, 39, 42, 45, 48, 51, 54, 57]
class Enumerator::Lazy
def filter_map
Lazy.new(self) do |holder, *values|
result = yield *values
holder << result if result
end
end
end
class Fizz
def initialize(head, tail)
@list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 3 == 0}.first(tail)
end
def fizz?(num)
search = @list
search.include?(num)
end
def drop(num)
list = @list
list.delete(num)
end
def to_a
@list.to_a
end
end
class Buzz
def initialize(head, tail)
@list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 5 == 0}.first(tail)
end
def buzz?(num)
search = @list
search.include?(num)
end
def drop(num)
list = @list
list.delete(num)
end
def to_a
@list.to_a
end
end
class FizzBuzz
def initialize(head, tail)
@list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 15 == 0}.first(tail)
end
def fizzbuzz?(num)
search = @list
search.include?(num)
end
def to_a
@list.to_a
end
def drop(num)
list = @list
list.delete(num)
end
end
stopper = 100
@fizz = Fizz.new(1,100)
@buzz = Buzz.new(1,100)
@fizzbuzz = FizzBuzz.new(1,100)
def min(v, n)
if v == 1
puts "Fizz: #{n}"
@fizz::drop(n)
elsif v == 2
puts "Buzz: #{n}"
@buzz::drop(n)
else
puts "FizzBuzz: #{n}"
@fizzbuzz::drop(n)
end
end
(@fizz.to_a & @fizzbuzz.to_a).map{|d| @fizz::drop(d)}
(@buzz.to_a & @fizzbuzz.to_a).map{|d| @buzz::drop(d)}
while @fizz.to_a.min < stopper or @buzz.to_a.min < stopper or @fizzbuzz.to_a.min < stopper
f, b, fb = @fizz.to_a.min, @buzz.to_a.min, @fizzbuzz.to_a.min
min(1,f) if f < fb and f < b
min(2,b) if b < f and b < fb
min(0,fb) if fb < b and fb < f
end
An example using string interpolation:
(1..100).each do |n|
v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}"
puts v.empty? ? n : v
end
Interpolation inspired one-liner:
1.upto(100) { |n| puts "#{'Fizz' if n % 3 == 0}#{'Buzz' if n % 5 == 0}#{n if n % 3 != 0 && n % 5 != 0}" }
An example using append:
1.upto 100 do |n|
r = ''
r << 'Fizz' if n % 3 == 0
r << 'Buzz' if n % 5 == 0
r << n.to_s if r.empty?
puts r
end
Yet another solution:
1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i }
Yet another solution:
1.upto(100){|i|puts'FizzBuzz '[n=i**4%-15,n+13]||i}
Used Enumerable#cycle:
f = [nil, nil, :Fizz].cycle
b = [nil, nil, nil, nil, :Buzz].cycle
(1..100).each do |i|
puts "#{f.next}#{b.next}"[/.+/] || i
end
After beforehand preparing the Array which put the number from 1 to 100, it processes.
seq = *0..100
{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}}
puts seq.drop(1)
Monkeypatch example:
class Integer
def fizzbuzz
v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}"
v.empty? ? self : v
end
end
puts *(1..100).map(&:fizzbuzz)
Without mutable variables or inline printing.
fizzbuzz = ->(i) do
(i%15).zero? and next "FizzBuzz"
(i%3).zero? and next "Fizz"
(i%5).zero? and next "Buzz"
i
end
puts (1..100).map(&fizzbuzz).join("\n")
Jump anywhere#Ruby has a worse example of FizzBuzz, using a continuation!
Using Ruby 3's Pattern Matching:
1.upto(100) do |n|
puts case [(n % 3).zero?, (n % 5).zero?]
in true, false
"Fizz"
in false, true
"Buzz"
in true, true
"FizzBuzz"
else
n
end
end
Ruby with RSpec
This is a solution to FizzBuzz using Test-Driven Development (In this case, with Ruby and RSpec). You will need to set up the correct file structure first, with /lib and /spec directories in your root.
Your spec/fizzbuzz_spec.rb file should like this:
require 'fizzbuzz'
describe 'FizzBuzz' do
context 'knows that a number is divisible by' do
it '3' do
expect(is_divisible_by_three?(3)).to be_true
end
it '5' do
expect(is_divisible_by_five?(5)).to be_true
end
it '15' do
expect(is_divisible_by_fifteen?(15)).to be_true
end
end
context 'knows that a number is not divisible by' do
it '3' do
expect(is_divisible_by_three?(1)).not_to be_true
end
it '5' do
expect(is_divisible_by_five?(1)).not_to be_true
end
it '15' do
expect(is_divisible_by_fifteen?(1)).not_to be_true
end
end
context 'while playing the game it returns' do
it 'the number' do
expect(fizzbuzz(1)).to eq 1
end
it 'Fizz' do
expect(fizzbuzz(3)).to eq 'Fizz'
end
it 'Buzz' do
expect(fizzbuzz(5)).to eq 'Buzz'
end
it 'FizzBuzz' do
expect(fizzbuzz(15)).to eq 'FizzBuzz'
end
end
end
There are many ways to get these tests to pass. Here is an example solution of what your lib/fizzbuzz.rb file could look like:
def fizzbuzz(number)
return 'FizzBuzz' if is_divisible_by_fifteen?(number)
return 'Buzz' if is_divisible_by_five?(number)
return 'Fizz' if is_divisible_by_three?(number)
number
end
def is_divisible_by_three?(number)
is_divisible_by(number, 3)
end
def is_divisible_by_five?(number)
is_divisible_by(number, 5)
end
def is_divisible_by_fifteen?(number)
is_divisible_by(number, 15)
end
def is_divisible_by(number, divisor)
number % divisor == 0
end
When writing Test Driven code, it's important to remember that you should use the Red, Green, Refactor cycle. Simply writing each of these code snippets independently would go against everything TDD is about. Here is a good video that takes you through the process of writing this FizzBuzz implementation using Ruby & RSpec.
Run BASIC
See FizzBuzz/Basic
Rust
Basic example with a for loop and match:
fn main() {
for i in 1..=100 {
match (i % 3, i % 5) {
(0, 0) => println!("fizzbuzz"),
(0, _) => println!("fizz"),
(_, 0) => println!("buzz"),
(_, _) => println!("{}", i),
}
}
}
Using an iterator and immutable data:
use std::borrow::Cow;
fn main() {
(1..=100)
.map(|n| match (n % 3, n % 5) {
(0, 0) => "FizzBuzz".into(),
(0, _) => "Fizz".into(),
(_, 0) => "Buzz".into(),
_ => Cow::from(n.to_string()),
})
.for_each(|n| println!("{:?}", n));
}
A folding iterator version, buffered with a single string allocation, by making use of expressions the write!
macro.
use std::fmt::Write;
fn fizzbuzz() -> String {
(1..=100).fold(String::new(), |mut output, x| {
let fizz = if x % 3 == 0 { "fizz" } else { "" };
let buzz = if x % 5 == 0 { "buzz" } else { "" };
if fizz.len() + buzz.len() != 0 {
output + fizz + buzz + "\n"
} else {
write!(&mut output, "{}", x).unwrap();
output + "\n"
}
})
}
fn main() {
println!("{}", fizzbuzz());
}
Or the ultimate optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout.
#![no_std]
#![feature(asm, lang_items, libc, no_std, start)]
extern crate libc;
const LEN: usize = 413;
static OUT: [u8; LEN] = *b"\
1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n\
16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n\
31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n\
46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n\
61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n\
76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n\
91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n";
#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
unsafe {
asm!(
"
mov $$1, %rax
mov $$1, %rdi
mov $0, %rsi
mov $1, %rdx
syscall
"
:
: "r" (&OUT[0]) "r" (LEN)
: "rax", "rdi", "rsi", "rdx"
:
);
}
0
}
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "panic_fmt"] extern fn panic_fmt() {}
Salmon
iterate (x; [1...100])
((x % 15 == 0) ? "FizzBuzz" :
((x % 3 == 0) ? "Fizz" :
((x % 5 == 0) ? "Buzz" : x)))!;
or
iterate (x; [1...100])
{
if (x % 15 == 0)
"FizzBuzz"!
else if (x % 3 == 0)
"Fizz"!
else if (x % 5 == 0)
"Buzz"!
else
x!;
};
SAS
data _null_;
do i=1 to 100;
if mod(i,15)=0 then put "FizzBuzz";
else if mod(i,5)=0 then put "Buzz";
else if mod(i,3)=0 then put "Fizz";
else put i;
end;
run;
Sather
class MAIN is
main is
loop i ::= 1.upto!(100);
s:STR := "";
if i % 3 = 0 then s := "Fizz"; end;
if i % 5 = 0 then s := s + "Buzz"; end;
if s.length > 0 then
#OUT + s + "\n";
else
#OUT + i + "\n";
end;
end;
end;
end;
Scala
Idiomatic scala code
object FizzBuzz extends App {
1 to 100 foreach { n =>
println((n % 3, n % 5) match {
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n
})
}
}
Geeky over-generalized solution ☺
def replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] =
rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) =>
a fold(_ => b, s => b fold(_ => a, t => Right(s + t))))
def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity)
1 to 100 map fizzbuzz foreach println
By a two-liners geek
def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMet
for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))
One-liner geek
for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))
Functional Scala
def fizzBuzzTerm(n: Int): String =
if (n % 15 == 0) "FizzBuzz"
else if (n % 3 == 0) "Fizz"
else if (n % 5 == 0) "Buzz"
else n.toString
def fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)
Scala 3 (Dotty)
Written so as to introduce changes, with comments.
def fizzBuzzTerm(n: Int): String | Int = // union types
(n % 3, n % 5) match // optional semantic indentation; no braces
case (0, 0) => "FizzBuzz"
case (0, _) => "Fizz"
case (_, 0) => "Buzz"
case _ => n // no need for `.toString`, thanks to union type
end match // optional `end` keyword, with what it's ending
end fizzBuzzTerm // `end` also usable for identifiers
val fizzBuzz = // no namespace object is required; all top level
LazyList.from(1).map(fizzBuzzTerm)
@main def run(): Unit = // @main for main method; can take custom args
fizzBuzz.take(100).foreach(println)
Scheme
(do ((i 1 (+ i 1)))
((> i 100))
(display
(cond ((= 0 (modulo i 15)) "FizzBuzz")
((= 0 (modulo i 3)) "Fizz")
((= 0 (modulo i 5)) "Buzz")
(else i)))
(newline))
Using a recursive procedure.
(define (fizzbuzz x y)
(println
(cond (( = (modulo x 15) 0 ) "FizzBuzz")
(( = (modulo x 3) 0 ) "Fizz")
(( = (modulo x 5) 0 ) "Buzz")
(else x)))
(if (< x y) (fizzbuzz (+ x 1) y)))
(fizzbuzz 1 100)
Approach with maps and filters, easier to change, less readable than the previous.
(define (fizzbuzz x)
(let ([words '((3 . "Fizz")
(5 . "Buzz"))])
(define (fbm x)
(let ([w (map cdr (filter (lambda (wo) (= 0 (modulo x (car wo)))) words))])
(if (null? w) x (apply string-append w))))
(for-each (cut format #t "~a~%" <>) (map fbm (iota x 1 1)))))
(fizzbuzz 15)
Sed
#n
# doesn't work if there's no input
# initialize counters (0 = empty) and value
s/.*/ 0/
: loop
# increment counters, set carry
s/^\(a*\) \(b*\) \([0-9][0-9]*\)/\1a \2b \3@/
# propagate carry
: carry
s/ @/ 1/
s/9@/@0/
s/8@/9/
s/7@/8/
s/6@/7/
s/5@/6/
s/4@/5/
s/3@/4/
s/2@/3/
s/1@/2/
s/0@/1/
/@/b carry
# save state
h
# handle factors
s/aaa/Fizz/
s/bbbbb/Buzz/
# strip value if any factor
/z/s/[0-9]//g
# strip counters and spaces
s/[ab ]//g
# output
p
# restore state
g
# roll over counters
s/aaa//
s/bbbbb//
# loop until value = 100
/100/q
b loop
Using seq:
seq 100 | sed '/.*[05]$/s//Buzz/;n;s//Buzz/;n;s//Buzz/;s/^[0-9]*/Fizz/'
GNU sed
GNU sed has first~step address expression that matches every stepth line. This makes following one-liners possible.
Using seq:
seq 100 | sed '0~3 s/.*/Fizz/; 0~5 s/[0-9]*$/Buzz/'
Using yes:
yes | sed -n '0~3s/y/Fizz/;0~5s/y*$/Buzz/;tx;=;b;:x;p;100q'
Using the option -z (--zero-data) first introduced in GNU sed 4.2.2 (2012-12-22):
sed -nz '0~3s/^/Fizz/;0~5s/$/Buzz/;tx;=;b;:x;p;100q' /dev/zero | sed 'y/\c@/\n/'
Second invocation of sed translates null characters to newlines. The same could be achieved with tr \\0 \\n
Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 100 do
if number rem 15 = 0 then
writeln("FizzBuzz");
elsif number rem 5 = 0 then
writeln("Buzz");
elsif number rem 3 = 0 then
writeln("Fizz");
else
writeln(number);
end if;
end for;
end func;
SenseTalk
repeat 100
put "" into output
if the counter is a multiple of 3 then
put "Fizz" after output
end if
if the counter is a multiple of 5 then
put "Buzz" after output
end if
if output is empty then
put the counter into output
end if
put output
end repeat
SequenceL
import <Utilities/Conversion.sl>;
import <Utilities/Sequence.sl>;
main(args(2)) :=
let
result[i] :=
"FizzBuzz" when i mod 3 = 0 and i mod 5 = 0
else
"Fizz" when i mod 3 = 0
else
"Buzz" when i mod 5 = 0
else
intToString(i)
foreach i within 1 ... 100;
in
delimit(result, '\n');
Shale
#!/usr/local/bin/shale
string library
r var
i var
i 1 =
{ i 100 <= } {
r "" =
i 3 % 0 == { r r "fizz" concat string::() = } ifthen
i 5 % 0 == { r r "buzz" concat string::() = } ifthen
r "" equals string::() { i } { r } if i "%3d: %p\n" printf
i++
} while
Shen
(define fizzbuzz
101 -> (nl)
N -> (let divisible-by? (/. A B (integer? (/ A B)))
(cases (divisible-by? N 15) (do (output "Fizzbuzz!~%")
(fizzbuzz (+ N 1)))
(divisible-by? N 3) (do (output "Fizz!~%")
(fizzbuzz (+ N 1)))
(divisible-by? N 5) (do (output "Buzz!~%")
(fizzbuzz (+ N 1)))
true (do (output (str N))
(nl)
(fizzbuzz (+ N 1))))))
(fizzbuzz 1)
Alternative showing off other features like prolog integration and guards
(defprolog fizz
0 <-- (is _ (output "Fizz"));
N <-- (when (> N 0)) (is N1 (- N 3)) (fizz N1);
)
(defprolog buzz
0 <-- (is _ (output "Buzz"));
N <-- (when (> N 0)) (is N1 (- N 5)) (buzz N1);
)
(define none
[] -> true
[true | _] -> false
[_ | B] -> (none B)
)
(define fizzbuzz
N M -> (nl) where (> N M)
N M -> (do
(if (none [(prolog? (receive N) (fizz N)) (prolog? (receive N) (buzz N))])
(output (str N))
(output "!")
)
(nl)
(fizzbuzz (+ N 1) M)
)
)
(fizzbuzz 1 100)
Sidef
Structured:
{ |i|
if (i %% 3) {
print "Fizz"
i %% 5 && print "Buzz"
print "\n"
}
elsif (i %% 5) { say "Buzz" }
else { say i }
} * 100
Declarative:
func fizzbuzz({ _ %% 15 }) { "FizzBuzz" }
func fizzbuzz({ _ %% 5 }) { "Buzz" }
func fizzbuzz({ _ %% 3 }) { "Fizz" }
func fizzbuzz( n ) { n }
for n in (1..100) { say fizzbuzz(n) }
One-liner:
{|i|say "#{<Fizz>[i%3]}#{<Buzz>[i%5]}"||i}*100
Simula
begin
integer i;
for i := 1 step 1 until 100 do
begin
boolean fizzed;
fizzed := 0 = mod(i, 3);
if fizzed then
outtext("Fizz");
if mod(i, 5) = 0 then
outtext("Buzz")
else if not fizzed then
outint(i, 3);
outimage
end;
end
SkookumScript
Answer by printing out one of the 4 alternatives:
1.to 100
[
println(
if idx.mod(15) = 0 ["FizzBuzz"]
idx.mod(3) = 0 ["Fizz"]
idx.mod(5) = 0 ["Buzz"]
else [idx])
]
Answer by building up a string:
1.to 100
[
!str: ""
if idx.mod(3) = 0 [str += "Fizz"]
if idx.mod(5) = 0 [str += "Buzz"]
println(if str.empty? [idx] else [str])
]
Or doing initial bind in one step:
1.to 100
[
!str: if idx.mod(3) = 0 ["Fizz"] else [""]
if idx.mod(5) = 0 [str += "Buzz"]
println(if str.empty? [idx] else [str])
]
Slate
n@(Integer traits) fizzbuzz
[
output ::= ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: ['']) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: ['']).
output isEmpty ifTrue: [n printString] ifFalse: [output]
].
1 to: 100 do: [| :i | inform: i fizzbuzz]
Small
See FizzBuzz/EsoLang
Smalltalk
Since only GNU Smalltalk supports file-based programming, we'll be using its syntax.
Integer extend [
fizzbuzz [
| fb |
fb := '%<Fizz|>1%<Buzz|>2' % {
self \\ 3 == 0. self \\ 5 == 0 }.
^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ]
A Squeak/Pharo example using the Transcript window:
(1 to: 100) do:
[:n |
((n \\ 3)*(n \\ 5)) isZero
ifFalse: [Transcript show: n].
(n \\ 3) isZero
ifTrue: [Transcript show: 'Fizz'].
(n \\ 5) isZero
ifTrue: [Transcript show: 'Buzz'].
Transcript cr.]
The Squeak/Pharo examples below present possibilities using the powerful classes available. In this example, the dictionary can have as keys pairs of booleans and in the interaction the several boolean patterns select the string to be printed or if the pattern is not found the number itself is printed.
fizzbuzz := Dictionary with: #(true true)->'FizzBuzz'
with: #(true false)->'Fizz'
with: #(false true)->'Buzz'.
1 to: 100 do:
[ :i | Transcript show:
(fizzbuzz at: {i isDivisibleBy: 3. i isDivisibleBy: 5}
ifAbsent: [ i ]); cr]
Smalltalk does not have a case-select construct, but a similar effect can be attained using a collection and the #includes: method:
1 to: 100 do: [:n | |r|
r := n rem: 15.
Transcript show: (r isZero
ifTrue:['fizzbuzz']
ifFalse: [(#(3 6 9 12) includes: r)
ifTrue:['fizz']
ifFalse:[((#(5 10) includes: r))
ifTrue:['buzz']
ifFalse:[n]]]);
cr].
If the construction of the whole collection is done beforehand, Smalltalk provides a straightforward way of doing because collections can be heterogeneous (may contain any object):
fbz := (1 to: 100) asOrderedCollection.
3 to: 100 by: 3 do: [:i | fbz at: i put: 'Fizz'].
5 to: 100 by: 5 do: [:i | fbz at: i put: 'Buzz'].
15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz'].
fbz do: [:i | Transcript show: i; cr].
The approach building a dynamic string can be done as well:
1 to: 100 do: [:i | |fb s|
fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}.
fb at: 3 put: (fb first | fb second) not.
s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}.
Transcript show: (s expandMacrosWithArguments: fb); cr].
SNOBOL4
Merely posting a solution by Daniel Lyons
I = 1
LOOP FIZZBUZZ = ""
EQ(REMDR(I, 3), 0) :F(TRY_5)
FIZZBUZZ = FIZZBUZZ "FIZZ"
TRY_5 EQ(REMDR(I, 5), 0) :F(DO_NUM)
FIZZBUZZ = FIZZBUZZ "BUZZ"
DO_NUM IDENT(FIZZBUZZ, "") :F(SHOW)
FIZZBUZZ = I
SHOW OUTPUT = FIZZBUZZ
I = I + 1
LE(I, 100) :S(LOOP)
END
SNUSP
See FizzBuzz/EsoLang
SQL
Oracle SQL
SELECT CASE
WHEN MOD(level,15)=0 THEN 'FizzBuzz'
WHEN MOD(level,3)=0 THEN 'Fizz'
WHEN MOD(level,5)=0 THEN 'Buzz'
ELSE TO_CHAR(level)
END FizzBuzz
FROM dual
CONNECT BY LEVEL <= 100;
Or using Oracle's DECODE and NVL:
SELECT nvl(decode(MOD(level,3),0,'Fizz')||decode(MOD(level,5),0,'Buzz'),level)
FROM dual
CONNECT BY level<=100;
PostgreSQL specific
SELECT i, fizzbuzz
FROM
(SELECT i,
CASE
WHEN i % 15 = 0 THEN 'FizzBuzz'
WHEN i % 5 = 0 THEN 'Buzz'
WHEN i % 3 = 0 THEN 'Fizz'
ELSE NULL
END AS fizzbuzz
FROM generate_series(1,100) AS i) AS fb
WHERE fizzbuzz IS NOT NULL;
Using Generate_Series and tables only:
SELECT COALESCE(FIZZ || BUZZ, FIZZ, BUZZ, OUTPUT) AS FIZZBUZZ FROM
(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT
FROM GENERATE_SERIES(1,100)) F LEFT JOIN
(SELECT TEXT 'Fizz' AS FIZZ, GENERATE_SERIES AS FIZZ_SERIES FROM GENERATE_SERIES(0,100,3)) FIZZ ON
FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN
(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON
BUZZ.BUZZ_SERIES = F.FULL_SERIES;
Recursive Common Table Expressions (MSSQL 2005+)
WITH nums (n, fizzbuzz ) AS (
SELECT 1, CONVERT(nvarchar, 1) UNION ALL
SELECT
(n + 1) as n1,
CASE
WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz'
WHEN (n + 1) % 3 = 0 THEN 'Fizz'
WHEN (n + 1) % 5 = 0 THEN 'Buzz'
ELSE CONVERT(nvarchar, (n + 1))
END
FROM nums WHERE n < 100
)
SELECT n, fizzbuzz FROM nums
ORDER BY n ASC
OPTION ( MAXRECURSION 100 )
Generic SQL using a join
This should work in most RDBMSs, but you may need to change MOD(i,divisor) to i % divisor.
-- Load some numbers
CREATE TABLE numbers(i INTEGER);
INSERT INTO numbers VALUES(1);
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;
-- Define the fizzes and buzzes
CREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER);
INSERT INTO fizzbuzz VALUES('fizz', 3);
INSERT INTO fizzbuzz VALUES('buzz', 5);
INSERT INTO fizzbuzz VALUES('fizzbuzz', 15);
-- Play fizzbuzz
SELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result
FROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0
GROUP BY i
HAVING i <= 100
ORDER BY i;
-- Tidy up
DROP TABLE fizzbuzz;
DROP TABLE numbers;
Squirrel
function Fizzbuzz(n) {
for (local i = 1; i <= n; i += 1) {
if (i % 15 == 0)
print ("FizzBuzz\n")
else if (i % 5 == 0)
print ("Buzz\n")
else if (i % 3 == 0)
print ("Fizz\n")
else {
print (i + "\n")
}
}
}
Fizzbuzz(100);
Stata
program define fizzbuzz
args n
forvalues i = 1/`n' {
if mod(`i',15) == 0 {
display "FizzBuzz"
}
else if mod(`i',5) == 0 {
display "Buzz"
}
else if mod(`i',3) == 0 {
display "Fizz"
}
else {
display `i'
}
}
end
Swahili
shughuli fizzBuzz() {
kwa i = 1 mpaka 100 {
kama (i % 15 == 0) {
andika("FizzBuzz")
} au (i % 5 == 0) {
andika("Buzz")
} au (i % 3 == 0) {
andika("Fizz")
} sivyo {
andika(i)
}
}
}
Swift
using a switch statement
for i in 1...100 {
switch (i % 3, i % 5) {
case (0, 0):
print("FizzBuzz")
case (0, _):
print("Fizz")
case (_, 0):
print("Buzz")
default:
print(i)
}
}
using two if statements and an Optional
for i in 1...100{
var s:String?
if i%3==0{s="Fizz"}
if i%5==0{s=(s ?? "")+"Buzz"}
print(s ?? i)
}
Symsyn
| FizzBuzz
1 I
if I LE 100
mod I 3 X
mod I 5 Y
if X EQ 0
'FIZZ' $S
if Y EQ 0
+ 'BUZZ' $S
endif
else
if Y EQ 0
'BUZZ' $S
else
~ I $S
endif
endif
$S []
+ I
goif
endif
Tailspin
templates fizz
$ mod 3 -> #
when <=0> do 'Fizz' !
end fizz
templates buzz
$ mod 5 -> #
when <=0> do 'Buzz' !
end buzz
[ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](when <=''> do $i ! otherwise $ !\)... -> '$;
' -> !OUT::write
Tcl
proc fizzbuzz {n {m1 3} {m2 5}} {
for {set i 1} {$i <= $n} {incr i} {
set ans ""
if {$i % $m1 == 0} {append ans Fizz}
if {$i % $m2 == 0} {append ans Buzz}
puts [expr {$ans eq "" ? $i : $ans}]
}
}
fizzbuzz 100
The following example shows Tcl's substitution mechanism that allows to concatenate the results of two successive commands into a string:
while {[incr i] < 101} {
set fb [if {$i % 3 == 0} {list Fizz}][if {$i % 5 == 0} {list Buzz}]
if {$fb ne ""} {puts $fb} {puts $i}
}
This version uses list rotation, so avoiding an explicit mod operation:
set f [lrepeat 5 "Fizz" {$i} {$i}]
foreach i {5 10} {lset f $i "Buzz"};lset f 0 "FizzBuzz"
for {set i 1} {$i <= 100} {incr i} {
puts [subst [lindex [set f [list {*}[lassign $f ff] $ff]] 0]]
}
TI-83 BASIC
See FizzBuzz/Basic
TI-83 Hex Assembly
TransFORTH
: FIZZBUZZ
101 1 DO
I 15 MOD 0 = IF
PRINT " FIZZBUZZ "
ELSE I 3 MOD 0 = IF
PRINT " FIZZ "
ELSE I 5 MOD 0 = IF
PRINT " BUZZ "
ELSE I . THEN THEN THEN
CR LOOP ;
True BASIC
See FizzBuzz/Basic
Turing
for i : 1 .. 100
if i mod 15 = 0 then
put "Fizzbuzz"
elsif i mod 5 = 0 then
put "Buzz"
elsif i mod 3 = 0 then
put "Fizz"
else
put i
end if
end for
TUSCRIPT
$$ MODE TUSCRIPT
LOOP n=1,100
mod=MOD (n,15)
SELECT mod
CASE 0
PRINT n," FizzBuzz"
CASE 3,6,9,12
PRINT n," Fizz"
CASE 5,10
PRINT n," Buzz"
DEFAULT
PRINT n
ENDSELECT
ENDLOOP
TXR
$ txr -p "(mapcar (op if @1 @1 @2) (repeat '(nil nil fizz nil buzz fizz nil nil fizz buzz nil fizz nil nil fizzbuzz)) (range 1 100))"
UNIX Shell
This solution should work with any Bourne-compatible shell:
i=1
while expr $i '<=' 100 >/dev/null; do
w=false
expr $i % 3 = 0 >/dev/null && { printf Fizz; w=true; }
expr $i % 5 = 0 >/dev/null && { printf Buzz; w=true; }
if $w; then echo; else echo $i; fi
i=`expr $i + 1`
done
Versions for specific shells
The other solutions work with fewer shells.
The next solution requires $(( ))
arithmetic expansion,
and it should work with every POSIX shell.
n=1
while [ 100 -ge n ]; do
if [ $((n % 15)) -eq 0 ]; then
echo FizzBuzz
elif [ $((n % 3)) -eq 0 ]; then
echo Fizz
elif [ $((n % 5)) -eq 0 ]; then
echo Buzz
else
echo $n
fi
n=$((n + 1))
done
The next solution requires the (( ))
command from the Korn Shell.
NUM=1
until ((NUM == 101)) ; do
if ((NUM % 15 == 0)) ; then
echo FizzBuzz
elif ((NUM % 3 == 0)) ; then
echo Fizz
elif ((NUM % 5 == 0)) ; then
echo Buzz
else
echo "$NUM"
fi
((NUM = NUM + 1))
done
A version using concatenation:
for ((n=1; n<=100; n++))
do
fb=''
[ $(( n % 3 )) -eq 0 ] && fb="${fb}Fizz"
[ $(( n % 5 )) -eq 0 ] && fb="${fb}Buzz"
[ -n "${fb}" ] && echo "${fb}" || echo "$n"
done
A version using some of the insane overkill of Bash 4:
command_not_found_handle () {
local Fizz=3 Buzz=5
[ $(( $2 % $1 )) -eq 0 ] && echo -n $1 && [ ${!1} -eq 3 ]
}
for i in {1..100}
do
Fizz $i && ! Buzz $i || echo -n $i
echo
done
Bash one-liner:
for i in {1..100};do ((($i%15==0))&& echo FizzBuzz)||((($i%5==0))&& echo Buzz;)||((($i%3==0))&& echo Fizz;)||echo $i;done
C Shell
@ n = 1
while ( $n <= 100 )
if ($n % 15 == 0) then
echo FizzBuzz
else if ($n % 5 == 0) then
echo Buzz
else if ($n % 3 == 0) then
echo Fizz
else
echo $n
endif
@ n += 1
end
Ursa
#
# fizzbuzz
#
decl int i
for (set i 1) (< i 101) (inc i)
if (= (mod i 3) 0)
out "fizz" console
end if
if (= (mod i 5) 0)
out "buzz" console
end if
if (not (or (= (mod i 3) 0) (= (mod i 5) 0)))
out i console
end if
out endl console
end for
Ursala
#import std
#import nat
fizzbuzz = ^T(&&'Fizz'! not remainder\3,&&'Buzz'! not remainder\5)|| ~&h+ %nP
#show+
main = fizzbuzz*t iota 101
V
[fizzbuzz
1 [>=] [
[[15 % zero?] ['fizzbuzz' puts]
[5 % zero?] ['buzz' puts]
[3 % zero?] ['fizz' puts]
[true] [dup puts]
] when succ
] while].
|100 fizzbuzz
Second try
(a compiler for fizzbuzz)
define a command that will generate a sequence
[seq [] swap dup [zero? not] [rolldown [dup] dip cons rollup pred] while pop pop].
create a quote that will return a quote that returns a quote if its argument is an integer (A HOF)
[check [N X F : [[integer?] [[X % zero?] [N F cons] if] if]] view].
Create a quote that will make sure that the above quote is applied correctly if given (Number Function) as arguments.
[func [[N F] : [dup N F check i] ] view map].
And apply it
100 seq [
[15 [pop 'fizzbuzz' puts]]
[5 [pop 'buzz' puts]]
[3 [pop 'fizz' puts]]
[1 [puts]]] [func dup] step
[i true] map pop
the first one is much better :)
Vala
int main() {
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) stdout.printf("Fizz\n");
if (i % 5 == 0) stdout.printf("Buzz\n");
if (i % 15 == 0) stdout.printf("FizzBuzz\n");
if (i % 3 != 0 && i % 5 != 0) stdout.printf("%d\n", i);
}
return 0;;
}
VAX Assembly
00000008 0000 1 len =8
00000008 0000 2 msg: .blkb len ;output buffer
0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field
00000000' 000C 4 .address msg ;pointer to buffer
00000012 0010 5 outlen: .blkw 1
4C 55 21 0000001A'010E0000' 0012 6 ctr: .ascid "!UL"
001D 7
0000 001D 8 .entry start,0
52 7C 001F 9 clrq r2 ;r2+r3 64bit
52 D6 0021 10 incl r2 ;start index 1
0023 11 loop:
E2 AF B4 0023 12 clrw desc ;assume not fizz and or buzz
55 D7 AF 9E 0026 13 movab msg, r5 ;pointer to message buffer
54 50 52 03 7B 002A 14 ediv #3,r2,r0,r4 ;divr.rl,divd.rq,quo.wl,rem.wl
54 D5 002F 15 tstl r4 ;remainder
0B 12 0031 16 bneq not_fizz ;not equal zero
0033 17
85 7A7A6966 8F D0 0033 18 movl #^a"fizz", (r5)+ ;add to message
CA AF 04 A0 003A 19 addw2 #4, desc ;and update length
003E 20 not_fizz:
54 50 52 05 7B 003E 21 ediv #5,r2,r0,r4
54 D5 0043 22 tstl r4
0B 12 0045 23 bneq not_buzz
0047 24
85 7A7A7562 8F D0 0047 25 movl #^a"buzz", (r5)+
B6 AF 04 A0 004E 26 addw2 #4, desc
0052 27 not_buzz:
B3 AF B5 0052 28 tstw desc ;fizz and or buzz?
1B 12 0055 29 bneq show_buffer ;neq - yes
0057 30
AD AF 08 B0 0057 31 movw #len, desc ;fao length limit
005B 32 $fao_s - ;eql -no
005B 33 ctrstr = ctr, - ;show number
005B 34 outlen = outlen, -
005B 35 outbuf = desc, -
005B 36 p1 = r2
96 AF A0 AF B0 006D 37 movw outlen, desc ;characters filled by fao
0072 38 show_buffer:
93 AF 7F 0072 39 pushaq desc
00000000'GF 01 FB 0075 40 calls #1, g^lib$put_output
9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml
04 0084 42 ret
0085 43 .end start
VBA
Option Explicit
Sub FizzBuzz()
Dim Tb(1 To 100) As Variant
Dim i As Integer
For i = 1 To 100
'Tb(i) = i ' move to Else
If i Mod 15 = 0 Then
Tb(i) = "FizzBuzz"
ElseIf i Mod 5 = 0 Then
Tb(i) = "Buzz"
ElseIf i Mod 3 = 0 Then
Tb(i) = "Fizz"
Else
Tb(i) = i
End If
Next
Debug.Print Join(Tb, vbCrLf)
End Sub
As an alternative, testing each number only once:
Sub FizzBuzz()
Dim i As Integer
Dim T(1 To 99) As Variant
For i = 1 To 99 Step 3
T(i + 0) = IIf((i + 0) Mod 5 = 0, "Buzz", i)
T(i + 1) = IIf((i + 1) Mod 5 = 0, "Buzz", i + 1)
T(i + 2) = IIf((i + 2) Mod 5 = 0, "FizzBuzz", "Fizz")
Next i
Debug.Print Join(T, ", ") & ", Buzz"
End Sub
VBScript
For i = 1 To 100
If i Mod 15 = 0 Then
WScript.Echo "FizzBuzz"
ElseIf i Mod 5 = 0 Then
WScript.Echo "Buzz"
ElseIf i Mod 3 = 0 Then
WScript.Echo "Fizz"
Else
WScript.Echo i
End If
Next
An Alternative
With WScript.StdOut
For i = 1 To 100
If i Mod 3 = 0 Then .Write "Fizz"
If i Mod 5 = 0 Then .Write "Buzz"
If .Column = 1 Then .WriteLine i Else .WriteLine ""
Next
End With
Verbexx
@LOOP init:{@VAR t3 t5; @VAR i = 1} while:(i <= 100) next:{i++}
{
t3 = (i % 3 == 0);
t5 = (i % 5 == 0);
@SAY ( @CASE when:(t3 && t5) { 'FizzBuzz }
when: t3 { 'Fizz }
when: t5 { 'Buzz }
else: { i }
);
};
Verilog
module main;
integer number;
initial begin
for(number = 1; number < 100; number = number + 1) begin
if (number % 15 == 0) $display("FizzBuzz");
else begin
if(number % 3 == 0) $display("Fizz");
else begin
if(number % 5 == 0) $display("Buzz");
else $display(number);
end
end
end
$finish;
end
endmodule
VHDL
entity fizzbuzz is
end entity fizzbuzz;
architecture beh of fizzbuzz is
procedure fizzbuzz(num : natural) is
begin
if num mod 15 = 0 then
report "FIZZBUZZ";
elsif num mod 3 = 0 then
report "FIZZ";
elsif num mod 5 = 0 then
report "BUZZ";
else
report to_string(num);
end if;
end procedure fizzbuzz;
begin
p_fizz : process is
begin
for i in 1 to 100 loop
fizzbuzz(i);
end loop;
wait for 200 us;
end process p_fizz;
end architecture beh;
Vim Script
for i in range(1, 100)
if i % 15 == 0
echo "FizzBuzz"
elseif i % 5 == 0
echo "Buzz"
elseif i % 3 == 0
echo "Fizz"
else
echo i
endif
endfor
Visual Basic .NET
See FizzBuzz/Basic
Visual Prolog
implement main
open core, console
class predicates
fizzbuzz : (integer) -> string procedure (i).
clauses
fizzbuzz(X) = S :- X mod 15 = 0, S = "FizzBuzz", !.
fizzbuzz(X) = S :- X mod 5 = 0, S = "Buzz", !.
fizzbuzz(X) = S :- X mod 3 = 0, S = "Fizz", !.
fizzbuzz(X) = S :- S = toString(X).
run() :-
foreach X = std::fromTo(1,100) do
write(fizzbuzz(X)), write("\n")
end foreach,
succeed.
end implement main
goal
console::runUtf8(main::run).
Vlang
Updated for Vlang version 0.2.2
const (
fizz = Tuple{true, false}
buzz = Tuple{false, true}
fizzbuzz = Tuple{true, true}
)
struct Tuple{
val1 bool
val2 bool
}
fn fizz_or_buzz( val int ) Tuple {
return Tuple{ val % 3 == 0, val % 5 == 0 }
}
fn fizzbuzz( n int ) {
for i in 1..(n + 1) {
match fizz_or_buzz(i) {
fizz { println('Fizz') }
buzz { println('Buzz') }
fizzbuzz { println('FizzBuzz') }
else { println(i) }
}
}
}
fn main(){
fizzbuzz(15)
}
- Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Basic example with a for loop and match:
fn main() {
mut i := 1
for i <= 100 {
match true {
i % 15 == 0 { println('FizzBuzz') }
i % 3 == 0 { println('Fizz') }
i % 5 == 0 { println('Buzz') }
else { println(i) }
}
i++
}
}
Another basic example using the ubiquitous if/else (if) statement:
fn main() {
for i in 1..100 {
if i % 15 == 0 {
println('FizzBuzz')
} else if i % 3 == 0 {
println('Fizz')
} else if i % 5 == 0 {
println('Buzz')
} else {
println(i)
}
}
}
- Output:
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
VTL-2
10 N=1
20 #=30
30 #=N/3*0+%=0*110
40 #=N/5*0+%=0*130
50 #=!+30
60 ?=N
70 ?=""
80 N=N+1
90 #=100>N*20
100 #=999
110 ?="Fizz";
120 #=!
130 ?="Buzz";
140 #=!
180 #=70
Wart
for i 1 (i <= 100) ++i
prn (if (divides i 15)
"FizzBuzz"
(divides i 3)
"Fizz"
(divides i 5)
"Buzz"
:else
i)
WDTE
let io => import 'io';
let s => import 'stream';
let multiple of n => == (% n of) 0;
let fizzbuzz n => switch n {
multiple (* 3 5) => 'FizzBuzz';
multiple 3 => 'Fizz';
multiple 5 => 'Buzz';
default => n;
} -- io.writeln io.stdout;
s.range 1 101 -> s.map fizzbuzz -> s.drain;
Whitespace
See FizzBuzz/EsoLang
Wortel
@each &x!console.log x !*&x?{%%x 15 "FizzBuzz" %%x 5 "Buzz" %%x 3 "Fizz" x} @to 100
Wren
for (i in 1..100) {
if (i % 15 == 0) {
System.print("FizzBuzz")
} else if (i % 3 == 0) {
System.print("Fizz")
} else if (i % 5 == 0) {
System.print("Buzz")
} else {
System.print(i)
}
}
- Output:
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
X86 Assembly
; x86_64 linux nasm
section .bss
number resb 4
section .data
fizz: db "Fizz"
buzz: db "Buzz"
newLine: db 10
section .text
global _start
_start:
mov rax, 1 ; initialize counter
loop:
push rax
call fizzBuzz
pop rax
inc rax
cmp rax, 100
jle loop
mov rax, 60
mov rdi, 0
syscall
fizzBuzz:
mov r10, rax
mov r15, 0 ; boolean fizz or buzz
checkFizz:
xor rdx, rdx ; clear rdx for division
mov rbx, 3
div rbx
cmp rdx, 0 ; modulo result here
jne checkBuzz
mov r15, 1
mov rsi, fizz
mov rdx, 4
mov rax, 1
mov rdi, 1
syscall
checkBuzz:
mov rax, r10
xor rdx, rdx
mov rbx, 5
div rbx
cmp rdx, 0
jne finishLine
mov r15, 1
mov rsi, buzz
mov rdx, 4
mov rax, 1
mov rdi, 1
syscall
finishLine: ; print number if no fizz or buzz
cmp r15, 1
je nextLine
mov rax, r10
call printNum
ret
nextLine:
mov rsi, newLine
mov rdx, 1
mov rax, 1
mov rdi, 1
syscall
ret
printNum: ; write proper digits into number buffer
cmp rax, 100
jl lessThanHundred
mov byte [number], 49
mov byte [number + 1], 48
mov byte [number + 2], 48
mov rdx, 3
jmp print
lessThanHundred: ; get digits to write through division
xor rdx, rdx
mov rbx, 10
div rbx
add rdx, 48
cmp rax, 0
je lessThanTen
add rax, 48
mov byte [number], al
mov byte [number + 1], dl
mov rdx, 2
jmp print
lessThanTen:
mov byte [number], dl
mov rdx, 1
print:
mov byte [number + rdx], 10 ; add newline
inc rdx
mov rax, 1
mov rdi, 1
mov rsi, number
syscall
ret
XLISP
(defun fizzbuzz ()
(defun fizzb (x y)
(display (cond
((= (mod x 3) (mod x 5) 0) "FizzBuzz")
((= (mod x 3) 0) "Fizz")
((= (mod x 5) 0) "Buzz")
(t x)))
(newline)
(if (< x y)
(fizzb (+ x 1) y)))
(fizzb 1 100))
(fizzbuzz)
XMIDAS
startmacro
loop 100 count
calc/quiet three ^count 3 modulo
calc/quiet five ^count 5 modulo
if ^three eq 0 and ^five eq 0
say "fizzbuzz"
elseif ^three eq 0
say "fizz"
elseif ^five eq 0
say "buzz"
else
say ^count
endif
endloop
endmacro
Xojo
For i As Integer = 1 To 100
If i Mod 3 = 0 And i Mod 5 = 0 Then
Print("FizzBuzz")
ElseIf i Mod 3 = 0 Then
Print("Fizz")
ElseIf i Mod 5 = 0 Then
Print("Buzz")
Else
Print(Str(i))
End If
Next
An alternative syntax:
For i As Integer = 1 To 100
Select Case True
Case i Mod 3 = 0 And i Mod 5 = 0
Print("FizzBuzz")
Case i Mod 3 = 0
Print("Fizz")
Case i Mod 5 = 0
Print("Buzz")
Else
Print(Str(i))
End Select
Next
XPath 2.0
for $n in 1 to 100 return
concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])
...or alternatively...
for $n in 1 to 100 return
($n, 'Fizz', 'Buzz', 'FizzBuzz')[number(($n mod 3) = 0) + number(($n mod 5) = 0)*2 + 1]
XPL0
code CrLf=9, IntOut=11, Text=12;
int N;
[for N:= 1 to 100 do
[if rem(N/3)=0 then Text(0,"Fizz");
if rem(N/5)=0 then Text(0,"Buzz")
else if rem(N/3)#0 then IntOut(0,N);
CrLf(0);
];
]
- Output:
1 2 Fizz 4 Buzz Fizz 7 ... 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
XSLT
XSLT 1.0
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" encoding="utf-8"/>
<!-- Outputs a line for a single FizzBuzz iteration. -->
<xsl:template name="fizzbuzz-single">
<xsl:param name="n"/>
<!-- $s will be "", "Fizz", "Buzz", or "FizzBuzz". -->
<xsl:variable name="s">
<xsl:if test="$n mod 3 = 0">Fizz</xsl:if>
<xsl:if test="$n mod 5 = 0">Buzz</xsl:if>
</xsl:variable>
<!-- Output $s. If $s is blank, also output $n. -->
<xsl:value-of select="$s"/>
<xsl:if test="$s = ''">
<xsl:value-of select="$n"/>
</xsl:if>
<!-- End line. -->
<xsl:value-of select="' '"/>
</xsl:template>
<!-- Calls fizzbuzz-single over each value in a range. -->
<xsl:template name="fizzbuzz-range">
<!-- Default parameters: From 1 through 100 -->
<xsl:param name="startAt" select="1"/>
<xsl:param name="endAt" select="$startAt + 99"/>
<!-- Simulate a loop with tail recursion. -->
<!-- Loop condition -->
<xsl:if test="$startAt <= $endAt">
<!-- Loop body -->
<xsl:call-template name="fizzbuzz-single">
<xsl:with-param name="n" select="$startAt"/>
</xsl:call-template>
<!-- Increment counter, repeat -->
<xsl:call-template name="fizzbuzz-range">
<xsl:with-param name="startAt" select="$startAt + 1"/>
<xsl:with-param name="endAt" select="$endAt"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<!-- Main procedure -->
<xsl:template match="/">
<!-- Default parameters are used -->
<xsl:call-template name="fizzbuzz-range"/>
</xsl:template>
</xsl:stylesheet>
XSLT 1.0 With EXSLT
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
exclude-result-prefixes="xsl exsl">
<xsl:output method="text"/>
<xsl:template name="FizzBuzz" match="/">
<xsl:param name="n" select="1" />
<xsl:variable name="_">
<_><xsl:value-of select="$n" /></_>
</xsl:variable>
<xsl:apply-templates select="exsl:node-set($_)/_" />
<xsl:if test="$n < 100">
<xsl:call-template name="FizzBuzz">
<xsl:with-param name="n" select="$n + 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template match="_[. mod 3 = 0]">Fizz
</xsl:template>
<xsl:template match="_[. mod 5 = 0]">Buzz
</xsl:template>
<xsl:template match="_[. mod 15 = 0]" priority="1">FizzBuzz
</xsl:template>
<xsl:template match="_">
<xsl:value-of select="concat(.,'
')" />
</xsl:template>
</xsl:stylesheet>
XSLT 2.0
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of separator="
" select="
for $n in 1 to 100 return
concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])"/>
</xsl:template>
</xsl:stylesheet>
Yabasic
See FizzBuzz/Basic
Yorick
Iterative solution
for(i = 1; i <= 100; i++) {
if(i % 3 == 0)
write, format="%s", "Fizz";
if(i % 5 == 0)
write, format="%s", "Buzz";
if(i % 3 && i % 5)
write, format="%d", i;
write, "";
}
Vectorized solution
output = swrite(format="%d", indgen(100));
output(3::3) = "Fizz";
output(5::5) = "Buzz";
output(15::15) = "FizzBuzz";
write, format="%s\n", output;
Z80 Assembly
zkl
foreach n in ([1..100]) {
if(n % 3 == 0) print("Fizz");
if(not (n%5)) "Buzz".print();
if(n%3 and n%5) print(n);
println();
}
Or, using infinite lazy sequences:
fcn f(a,b,c){ a+b and a+b or c }
Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..])
.walk(100).concat("\n").println();
More of the same:
Walker.cycle(0,0,"Fizz",0,"Buzz","Fizz",0,0,"Fizz","Buzz",0,"Fizz",0,0,"FizzBuzz")
.zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println();
- Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...
ZX Spectrum Basic
10 DEF FN m(a,b)=a-INT (a/b)*b
20 FOR a=1 TO 100
30 LET o$=""
40 IF FN m(a,3)=0 THEN LET o$="Fizz"
50 IF FN m(a,5)=0 THEN LET o$=o$+"Buzz"
60 IF o$="" THEN LET o$=STR$ a
70 PRINT o$
80 NEXT a
- Programming Tasks
- Classic CS problems and programs
- Iteration
- Recursion
- Simple
- 11l
- 360 Assembly
- 6502 Assembly
- 68000 Assembly
- 8080 Assembly
- 8086 Assembly
- 8th
- AArch64 Assembly
- ABAP
- ACL2
- Action!
- ActionScript
- Ada
- ALGOL 68
- ALGOL-M
- ALGOL W
- AntLang
- APEX
- APL
- AppleScript
- Applesoft BASIC
- Arbre
- Arc
- ARM Assembly
- Arturo
- AsciiDots
- ASIC
- Asymptote
- ATS
- AutoHotkey
- AutoIt
- Avail
- AWK
- Axe
- Babel
- BaCon
- Bash
- BASIC
- BASIC256
- Batch File
- BBC BASIC
- Bc
- BCPL
- Beeswax
- Befunge
- Blz
- Boo
- BQN
- Bracmat
- Brainf***
- Brat
- BrightScript (for Roku)
- C
- C sharp
- C++
- Casio BASIC
- Cduce
- Ceylon
- Chapel
- Chef
- Clay
- Clipper
- CLIPS
- Clojure
- CLU
- CMake
- COBOL
- Coco
- Coconut
- CoffeeScript
- ColdFusion
- Comal
- Comefrom0x10
- Common Lisp
- Coq
- Cowgol
- Crystal
- CSS
- Cubescript
- D
- Dart
- Dc
- Delphi
- DeviousYarn
- Draco
- DUP
- DWScript
- Dyalect
- Déjà Vu
- E
- EasyLang
- ECL
- Eero
- Egel
- Eiffel
- Ela
- Elixir
- Elm
- Emacs Lisp
- Emojicode
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Falcon
- FALSE
- Fantom
- FBSL
- Fennel
- FOCAL
- Fermat
- Forth
- Fortran
- FreeBASIC
- Frege
- Frink
- FutureBasic
- Fōrmulæ
- Gambas
- GAP
- Genyris
- GFA Basic
- Gleam
- Go
- Golfscript
- Golo
- Gosu
- Groovy
- GW-BASIC
- Hare
- Haskell
- Hexiscript
- HicEst
- HolyC
- Hoon
- Huginn
- Hy
- I
- Icon
- Unicon
- Idris
- Inform 6
- Inform 7
- Io
- Ioke
- Iptscrae
- J
- Janet
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Kamailio Script
- Kaya
- KL1
- Klong
- Kotlin
- KQL
- KSI
- LabVIEW
- Lambdatalk
- Langur
- Lasso
- LaTeX
- Ifthen
- Intcalc
- Liberty BASIC
- LIL
- LiveCode
- LiveScript
- LLVM
- Lobster
- Logo
- LOLCODE
- LSE
- Lua
- Luck
- M2000 Interpreter
- M4
- Make
- Jot
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- MEL
- Mercury
- Metafont
- Microsoft Small Basic
- Min
- MiniScript
- MIPS Assembly
- Mirah
- ML
- Standard ML
- MLite
- MMIX
- Modula-2
- Modula-3
- Monte
- MontiLang
- MoonScript
- MUMPS
- Nanoquery
- NATURAL
- Neko
- Nemerle
- NetRexx
- Never
- NewLISP
- NewtonScript
- Nickle
- Nim
- Nix
- Oberon-2
- Objeck
- Objective-C
- OCaml
- Octave
- Oforth
- Ol
- OOC
- Order
- Oz
- PARI/GP
- Pascal
- PDP-8 Assembly
- Peloton
- Perl
- Phix
- Phix/basics
- PHL
- PHP
- Picat
- PicoLisp
- Pike
- PILOT
- PIR
- PL/I
- PL/M
- PL/SQL
- Pony
- Pop11
- PostScript
- Potion
- PowerShell
- Processing
- Prolog
- PureBasic
- Pyret
- Python
- Q
- QB64
- Quackery
- R
- Racket
- Raku
- RapidQ
- Rascal
- Raven
- REALbasic
- ReasonML
- REBOL
- Red
- Retro
- REXX
- Ring
- Robotic
- Rockstar
- Ruby
- Ruby with RSpec
- Run BASIC
- Rust
- Salmon
- SAS
- Sather
- Scala
- Scheme
- Sed
- Seed7
- SenseTalk
- SequenceL
- Shale
- Shen
- Sidef
- Simula
- SkookumScript
- Slate
- Small
- Smalltalk
- SNOBOL4
- SNUSP
- SQL
- Squirrel
- Stata
- Swahili
- Swift
- Symsyn
- Tailspin
- Tcl
- TI-83 BASIC
- TI-83 Hex Assembly
- TransFORTH
- True BASIC
- Turing
- TUSCRIPT
- TXR
- UNIX Shell
- C Shell
- Ursa
- Ursala
- V
- Vala
- VAX Assembly
- VBA
- VBScript
- Verbexx
- Verilog
- VHDL
- Vim Script
- Visual Basic .NET
- Visual Prolog
- Vlang
- VTL-2
- Wart
- WDTE
- Whitespace
- Wortel
- Wren
- X86 Assembly
- XLISP
- XMIDAS
- Xojo
- XPath 2.0
- XPL0
- XSLT
- Yabasic
- Yorick
- Z80 Assembly
- Zkl
- ZX Spectrum Basic
- Pages with too many expensive parser function calls