FizzBuzz: Difference between revisions
→{{header|Python}}: wrap examples in python tags |
|||
Line 603: | Line 603: | ||
</python> |
</python> |
||
And a shorter version, using a list comprehension and logical expressions |
And a shorter, but less clear version, using a list comprehension and logical expressions: |
||
<python> |
<python> |
||
for i in range(1, 101): |
for i in range(1, 101): |
Revision as of 04:24, 23 November 2008
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". [1]
FizzBuzz was presented as the lowest level of comprehension required to illustrate adequacy. [2]
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
APL
⎕IO←0 (L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]
AWK
BEGIN { for (NUM=1; NUM<=100; NUM++) if (NUM % 15 == 0) {print "FizzBuzz"} else if (NUM % 3 == 0) {print "Fizz"} else if (NUM % 5 == 0) {print "Buzz"} else {print NUM} }
BASIC
If/else ladder approach
FOR A = 1 TO 100 IF A MOD 15 = 0 THEN PRINT "FizzBuzz" ELSE IF A MOD 3 = 0 THEN PRINT "Fizz" ELSE IF A MOD 5 = 0 THEN PRINT "Buzz" ELSE PRINT A END IF NEXT A
Concatenation approach
FOR A = 1 TO 100 OUT$ = "" IF A MOD 3 = 0 THEN OUT$ = OUT& + "Fizz" END IF IF A MOD 5 = 0 THEN OUT$ = OUT$ + "Buzz" END IF IF OUT$ = "" THEN OUT$ = OUT$ + A END IF PRINT OUT$ NEXT A
See also: RapidQ
C
#include<stdio.h> int main (void) { int i; for (i = 1; i <= 100; i++) { if (!(i % 15)) printf ("FizzBuzz\n"); else if (!(i % 3)) printf ("Fizz\n"); else if (!(i % 5)) printf ("Buzz\n"); else printf ("%d\n", i); } return 0; }
C++
<cpp>
- include <iostream>
using namespace std; int main () {
int i; for (i = 0; i <= 100; i++) { if (!(i % 15)) cout << "FizzBuzz" << endl; else if (!(i % 3)) cout << "Fizz" << endl; else if (!(i % 5)) cout << "Buzz" << endl; else cout << i << endl; } return 0;
} </cpp>
Alternate version not using modulo 15: <cpp>
- include <iostream>
int main() {
for (int i = 0; i <= 100; ++i) { bool fizz = !(i % 3); bool buzz = !(i % 5); if (fizz) std::cout << "Fizz"; if (buzz) std::cout << "Buzz"; if (!fizz && !buzz) std::cout << i; std::cout << std::endl; }
} </cpp>
C#
<csharp> using System;
namespace RosettaCode.FizzBuzz {
class Program { static void Main(string[] args) { for (int i = 1; i <= 100; i++) { string output = ""; if (i % 3 == 0) output += "Fizz"; if (i % 5 == 0) output += "Buzz"; if (String.IsNullOrEmpty(output)) output = i.ToString(); Console.WriteLine(output); } } }
} </csharp>
Common Lisp
(defun fizzbuzz () (loop for x from 1 to 100 do (print (cond ((zerop (mod x 15)) "FizzBuzz") ((zerop (mod x 3)) "Fizz") ((zerop (mod x 5)) "Buzz") (t x)))))
(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)))))
D
module fizzbuzz; import std.stdio; import std.string ; // if-else void fizzBuzz(int n) { for(int i = 1 ; i <= n; i++) if (!(i%15)) writef("FizzBuzz") ; else if (!(i%3)) writef("Fizz") ; else if (!(i%5)) writef("Buzz") ; else writef(i) ; writefln() ; } // use switch case void fizzBuzz_s(int n) { for(int i = 1 ; i <= n; i++) switch(i%15) { case 0: writef("FizzBuzz") ; break ; case 3,6,9,12: writef("Fizz") ; break ; case 5,10: writef("Buzz") ; break ; default: writef(i) ; } writefln() ; } // recursive with concatenation string fizzBuzz_r(int n){ string s = "" ; if (n == 0) return s ; if(!(n % 5)) s = "Buzz"~ s ; if(!(n % 3)) s = "Fizz" ~ s ; if (s == "") s = toString(n) ; return fizzBuzz_r(n-1) ~ s ; } // alternative recursive string fizzBuzz_r2(int n){ return (n>0) ? fizzBuzz_r2(n-1) ~ (n % 15 ? n % 5 ? n % 3 ? toString(n) :"Fizz" : "Buzz" : "FizzBuzz") : ""; } void main() { fizzBuzz(100) ; fizzBuzz_s(100) ; writefln(fizzBuzz_r(100)) ; writefln(fizzBuzz_r2(100)) ; for(int i = 1 ; i <= 100;i++) writef("%s", i % 15 ? i % 5 ? i % 3 ? toString(i) :"Fizz" : "Buzz" : "FizzBuzz") ; }
E
for i in 1..100 { println(switch ([i % 3, i % 5]) { match [==0, ==0] { "FizzBuzz" } match [==0, _ ] { "Fizz" } match [_, ==0] { "Buzz" } match _ { i } }) }
Factor
IN: fizzbuzz USING: math kernel io ; : divides? ( m n -- ? ) mod 0 = ; : fizz ( n -- str ) 3 divides? [ "Fizz" ] [ "" ] if ; : buzz ( n -- str ) 5 divides? [ "Buzz" ] [ "" ] if ; : fizzbuzz ( n -- str ) dup fizz over buzz append dup empty? [ nip ] [ drop number>string ] if ; : main ( -- ) 100 [ 1+ fizzbuzz print ] each ; MAIN: main
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
Fortran
In ANSI FORTRAN 66 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
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
Groovy
for (i in 1..100) { println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i }
Haskell
Variant directly implementing the specification:
output x | x3 && x5 = "FizzBuzz" | x3 = "Fizz" | x5 = "Buzz" | otherwise = show x where x3 = x `mod` 3 == 0 x5 = x `mod` 5 == 0 answer = map output [1..100]
J
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
Java
If/else ladder
<java>public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ if(i % 15 == 0){ System.out.println("FizzBuzz"); }else if(i % 3 == 0){ System.out.println("Fizz"); }else if(i % 5 == 0){ System.out.println("Buzz"); }else{ System.out.println(i); } } } }</java>
Concatenation
<java>public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ String output = ""; if(i % 3 == 0) output += "Fizz"; if(i % 5 == 0) output += "Buzz"; if(output.equals("")) output += i; System.out.println(output); } } }</java>
Ternary operator
<java>public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ System.out.println(i % 15 != 0 ? i % 5 != 0 ? i % 3 != 0 ? i : "Fizz" : "Buzz" : "FizzBuzz" ;); } } }</java>
Recursive
<java>public String fizzBuzz(int n){
String s = ""; if (n == 0) return s; if((n % 5) == 0) s = "Buzz" + s; if((n % 3) == 0) s = "Fizz" + s; if (s.equals("")) s = n + ""; return fizzBuzz(n-1) + s;
}</java>
Alternative Recursive
<java>public String fizzBuzz(int n){
return (n>0) ? fizzBuzz(n-1) + (n % 15 != 0? n % 5 != 0? n % 3 != 0? (n+"") :"Fizz" : "Buzz" : "FizzBuzz") : "";
}</java>
JavaScript
for (var i = 1; i <= 100; i++) { if (i % 15 == 0) { print("FizzBuzz"); } else if (i % 3 == 0) { print("Fizz"); } else if (i % 5 == 0) { print("Buzz"); } else { print(i); } }
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) ) )
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"); Out.Ln; ELSIF i MOD 5 = 0 THEN Out.String("Buzz"); Out.Ln; ELSIF i MOD 3 = 0 THEN Out.String("Fizz"); Out.Ln; ELSE Out.Int(i,0); Out.Ln; END; END; END FizzBuzz.
OCaml
<ocaml>let output x =
match x mod 3 = 0, x mod 5 = 0 with true, true -> "FizzBuzz" | true, false -> "Fizz" | false, true -> "Buzz" | false, false -> string_of_int x
let _ =
for i = 1 to 100 do print_endline (output i) done</ocaml>
Perl
<perl>foreach (1 .. 100) {
if (0 == $_ % 15) { print "FizzBuzz\n"; } elsif (0 == $_ % 3) { print "Fizz\n"; } elsif (0 == $_ % 5) { print "Buzz\n"; } else { print "$_\n"; };
};</perl>
More concisely:
<perl>sub f { $_[0] % $_[1] ? : $_[2] } print f($_, 3, 'Fizz') . f($_, 5, 'Buzz') || $_, "\n"
foreach 1 .. 100;</perl>
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"; } ?>
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
Python
<python> 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
</python>
And a shorter, but less clear version, using a list comprehension and logical expressions: <python> for i in range(1, 101):
words = [word for n, word in ((3, 'Fizz'), (5, 'Buzz')) if not i % n] print .join(words) or i
</python>
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
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
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) print "\n" end
Scheme
<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))</scheme>
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;
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 ]
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 :)
Visual Basic .NET
Platform: .NET
Sub Main() For i = 1 To 100 If i Mod 15 = 0 Then Console.WriteLine("FizzBuzz") ElseIf i Mod 5 = 0 Then Console.WriteLine("Buzz") ElseIf i Mod 3 = 0 Then Console.WriteLine("Fizz") Else Console.WriteLine(i) End If Next End Sub
UNIX Shell
for n in `seq 1 100`; do if [ $(($n % 15)) = 0 ]; then echo FizzBuzz elif [ $(($n % 3)) = 0 ]; then echo Fizz elif [ $(($n % 5)) = 0 ]; then echo Buzz else echo $n fi done
A more portable version:
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