See here [1]
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".
Disclaimer: I do realize this is easy, and I understand the content of the Coding Horror post I just linked to
Golfing is easy. How large can you make it?
Enterprise FizzBuzz [1] is written in C# and weighs in at 12 classes and 3 interfaces (not including the main program driver). It comes with a suite of unit tests written in MbUnit. It's fairly loosely coupled but I really should update it for C# 3.5.
[1] http://code.google.com/p/fizzbuzz/You people tend to complicate things a lot, huh?
@echo off
echo 1
echo 2
echo Fizz
echo 4
echo Buzz
echo Fizz
echo 7
echo 8
echo Fizz
echo Buzz
echo 11
echo Fizz
echo 13
echo 14
echo FizzBuzz
echo 16
echo 17
echo Fizz
echo 19
echo Buzz
echo Fizz
echo 22
echo 23
echo Fizz
echo Buzz
echo 26
echo Fizz
echo 28
echo 29
echo FizzBuzz
echo 31
echo 32
echo Fizz
echo 34
echo Buzz
echo Fizz
echo 37
echo 38
echo Fizz
echo Buzz
echo 41
echo Fizz
echo 43
echo 44
echo FizzBuzz
echo 46
echo 47
echo Fizz
echo 49
echo Buzz
echo Fizz
echo 52
echo 53
echo Fizz
echo Buzz
echo 56
echo Fizz
echo 58
echo 59
echo FizzBuzz
echo 61
echo 62
echo Fizz
echo 64
echo Buzz
echo Fizz
echo 67
echo 68
echo Fizz
echo Buzz
echo 71
echo Fizz
echo 73
echo 74
echo FizzBuzz
echo 76
echo 77
echo Fizz
echo 79
echo Buzz
echo Fizz
echo 82
echo 83
echo Fizz
echo Buzz
echo 86
echo Fizz
echo 88
echo 89
echo FizzBuzz
echo 91
echo 92
echo Fizz
echo 94
echo Buzz
echo Fizz
echo 97
echo 98
echo Fizz
echo Buzz
Don't forget lolcode...http://lolcode.com/contributions/cheezburger-fizzbuzz
(Not My Code)
For the clicky impaired:
HAI
BTW LOL I HAS A FIZZBUZZ EXAMPLE
CAN HAS STDIO?
I HAS A NUMBAR
LOL NUMBAR R 0
I HAS A MACKSIMUM
LOL MACKSIMUM R 100
IM IN YR LOOPZ
LOL NUMBAR R NUMBAR UP 1
I HAS A NUMBAR_IZ_CHEEZ
LOL NUMBAR_IZ_CHEEZ R 0
I HAS A NUMBAR_IZ_BURGER
LOL NUMBAR_IZ_BURGER R 0
I HAS A COUNTAR
LOL COUNTAR R 0
I HAS A MAX_COUNTAR
LOL MAX_COUNTAR R NUMBAR OVAR 3
IM IN YR LOOP
LOL COUNTAR R COUNTAR UP 1
BTW I CHECKIN FOR CHEEZ LOL
I HAS A CHEEZ_NUMBAR
LOL CHEEZ_NUMBAR R COUNTAR TIEMZ 3
IZ CHEEZ_NUMBAR LIEK NUMBAR?
YARLY
LOL NUMBAR_IZ_CHEEZ R 1
KTHX
BTW I CHECKIN FOR BURGER LOL
I HAS A BURGER_NUMBAR
LOL BURGER_NUMBAR R COUNTAR TIEMZ 5
IZ BURGER_NUMBAR LIEK NUMBAR?
YARLY
LOL NUMBAR_IZ_BURGER R 1
KTHX
IZ COUNTAR BIGR THAN MAX_COUNTAR?
YARLY
GTFO
KTHX
KTHX
IZ NUMBAR_IZ_CHEEZ LIEK 1 AND NUMBAR_IZ_BURGER LIEK 1?
YARLY
VISIBLE "CHEEZBURGER"
NOWAI
IZ NUMBAR_IZ_CHEEZ LIEK 1?
YARLY
VISIBLE "CHEEZ"
NOWAI
IZ NUMBAR_IZ_BURGER LIEK 1?
YARLY
VISIBLE "BURGER"
NOWAI
VISIBLE NUMBAR
KTHX
KTHX
KTHX
IZ NUMBAR UP 1 BIGR THAN MACKSIMUM?
YARLY
GTFO
KTHX
KTHX
KTHXBYE
Here's a long, yet golfed, perl solution:
( (
''))=~('('.'?'.'{'.("\`"|
'%').('['^'-').('`'|'!').
('`'|',').'"'.('['^'+').(
(( (
( ((
( ((
'[' ))))
)))))^(')')).(
'`'|"\)").(
( (
'`'))|'.').('['^
'/').'+'.('(').(
'`'^'&').(('`')|
((
((
')'))
))).+(
"\["^
( (
'!'))).('['^'!') .')'
.'['.'\\'.('$'). '_'.
'%'.('^'^(('`')| ((
( (
'-')))))).(']').
'.'.'('.('`'^'"'
).('['^'.').('['
^
((
((
'!'))))).(('[')^
'!').')'.('[').
'\\'.'$'.'_'
.
'%'.('^'^('`'|'+'
)).']'.'|'.'|'.'\\'.
'$'.'_'.','.'\\'.'$'
.+ (
((
(
(
(
(
(
'/')))))))).(
(
(
(
'`')))|
'&').('`'|"\/").(
'['^')').('{'^'[').('^'
^('`'|'/' ))."\.".
(( '.'
) )
. (
'^'^('`'|'/')).('^'^(('`')|
'.')).('^'^('`'|'.')).('!'^
( ( (
( ( (
( (
( (
'+' )
))))) )
)
))
).'"'
. (
'}').')');$:='.' ^'~'
;$~='@'|"\(";$^= ')'^
'[';$/='`'|"\."; $,
='('
^+ '}'
;($\) =(
('`'))| (
( "\!")); (
( $:))=')' ^
( '}');$~=
( '*')|
(( ((
'`')
)));
$^ =((
'+')) ^+
'_';$/= (
( "\&"))| (
( '@'));$, =
( '[')&'~'
; ($\)=
(( ((
',')
)))^ '|';
$:=('.')^ "\~";$~=
'@'|'(';$^=')'^"\[";$/=
'`'|'.';$,='('
^'}';$\
='`'|'!';$:="\)"^
'}';$~='*'|'`';$^="\+"^
('_');$/= '&'|'@';
$, =((
( "\[")))&
(( ('~')));$\=
(( ','))^ '|'
; ($:)= ((
'.'))^'~';$~='@'|'(';$^="\)"^
( '['); (
( $/))= (
'`')|'.';$,='('^'}';$\=('`')|
(( '!') )
;$:= (')')^ (
('}'));$~= (
(
(
(
(
(
(
(
(
( ((
'*') )) ))
))) ) )
))| ( (
'`' ));$^=
'+' ^((
(( (( '_'
) )))
) ) ;$/
='&'| '@'
;$, =
'[' &+
(( ((
( (
( (
( (( (
'~' )))))) )))
)));( ($\)) =','^"\|";
$:='.'^"\~"; $~="\@"|
"\(";$^=
')'^ '[';
$/=('`')| "\.";$,=
'('^'}';$\='`'|"\!";$:=
')'^'}';$~='*'
|+
'`';
($^)
=('+')^
'_';$/='&'|'@';$,
='['&'~';$\=','^'|';$:=
'.'^"\~"; $~="\@"|
(( '('
) )
; (
$^)=')'^'[';$/='`'|"\.";$,=
'('^'}';$\='`'|'!';$:="\)"^
( ( (
( ( (
( ( (
( ( (
( '}' ))
)) )))) )))
));( $~)= '*'|'`';$^
='+'^"\_";$/= '&'|'@';
$,='['&'~' ;$\=
"\,"^
(
'|');$:=('.')^
'~';$~='@'|"\(";
$^=')'^('[');$/=
((
((
(
'`')))))|'.';$,=
'('^'}';$\="\`"|
'!';$:=')'^"\}";
($~)
=( '*'
)|'`' ;(
$^)='+' ^
( '_');$/ =
( '&')|'@' ;
( $,)='['&
( '~');
$\ =(
',')
^'|'
;( $:)
='.'^ ((
"\~")); (
( ($~)))= (
( ('@')))| (
( '('));$^
= "\)"^
(( ((
'[')
))); ($/)
='`'|'.'; $,="\("^
'}';$\='`'|'!';$:="\)"^
'}';$~='*'|'`'
;$^='+'
^'_';$/='&'|"\@";
$,='['&'~';$\=','^"\|";
$:=('.')^ "\~";$~=
(( '@'
) )|'(';$^
=( ')')^'[';$/
=( "\`")| '.'
; ($,)= ((
'('))^'}';$\='`'|'!';$:="\)"^
( '}'); (
( $~))= (
'*')|'`';$^='+'^'_';$/=('&')|
(( '@') )
;$,= ('[')& (
('~'));$\= (
(
(
(
(
(
(
(
(
( ((
',') )) ))
))) ) )
))^ ( (
'|' ));$:=
'.' ^((
(( (( '~'
) )))
) ) ;$~
='@'| '('
;( ($^))=
(( ( (')'))))^
( (( '[')
) ); ($/)
= (( '`')
)| '.' ;$,=
"\("^ '}';$\ ='`'
|'!';$:=')'^'}' ;$~=
'*'|'`';$^= '+'^
'_'; ($/)
='&'|'@'; $,="\["&
'~';$\=','^'|';$:="\."^
'~';$~='@'|'('
;( ($^))=
')'^ '[';$/='`'|('.');$,=
'('^ '}';$\='`'|"\!";
$: ="\)"^
'}'; $~='*'|'`';$^=('+')^
'_'; $/='&'|('@');$,=
( '[')&'~'
;( $\)=','^'|'
;( ($:))= '.'
^ "\~"; $~
='@'|'(';$^=')'^'[';$/=('`')|
( '.'); (
( $,))= (
'(')^'}';$\='`'|'!';$:=(')')^
(( '}') )
;$~= ('*')| (
('`'));$^= (
(
(
(
(
(
(
(
(
((
'+')
))))))
) )))^'_';
$/ ='&'|'@';$,
=( "\[")& '~'
; ($\)= ((
','))^'|';$:='.'^'~';$~="\@"|
( '('); (
( $^))= (
')')^'[';$/='`'|'.';$,=('(')^
(( '}') )
;$\= ('`')| (
('!'));$:= (
(
')')
)^+
'}'
;$~
=((
'*'
))|
'`'
;$^
=
'+'^'_';$/='&'|"\@";$,=
'['&'~';$\=','^'|';$:='.'^
'~';$~='@'|'(';$^=')'^"\[";
( $/ )
= ('`')|
"\.";
($,)=
'('^'}';$\=
'`'|'!';$:=')'
^+ ((
( (
( (
( ((
'}') ))))
))));$~='*'|
"\`";$^=
( (
'+'))^'_';$/='&'
|'@';$,='['&'~';
$\=','^('|');$:=
((
((
'.'))
))^'~'
;($~)
=
( (
'@'))|'(';$^=')'^'[';$/=
'`'|'.';$,='('^'}';$\='`'
|
(
((
'!')
));(
$:
)=((
')')
)
^ (
'}');$~='*'|'`';$^="\+"^
'_';$/='&'|'@';$,='['&'~'
;
(
$\)="\,"^
'|';$:='.'^'~';$~=
'@'|'(';$^=')'^'[';$/=
"\`"| "\.";
$, =(
( (
( (
(( '('
))))) ))^((
'}'));$\='`'|('!');$:=
')'^'}';$~="\*"|
('`');$^=
'+'^'_';$/='&'|'@'
;$,='['&'~';$\=','^'|'
;($:) ='.'^
(( ((
( (
( (
(( '~'
))))) )))))
;$~='@'|'(';$^=')'^'['
;$/='`'|"\.";#;#
I'm kind of astounded that markdown doesn't have spoiler tags that would have conserved that vertical space...
A python solution that uses neither division nor modulus:
def div3():
while True:
yield ""
yield ""
yield "Fizz"
def div5():
while True:
yield ""
yield ""
yield ""
yield ""
yield "Buzz"
data = zip(div3(), div5(), range(1, 101))
for (fizz, buzz, value) in data:
print fizz + buzz or value
cycle
function, allowing e.g. div5 = cycle([''] * 4 + ['Buzz'])
. - intuited
The author asked for a language agnostic solution and so I will attack the question with pseudocode! We could argue about efficency all day but I find this the most readable form.
for every integer 1 to 100
if the integer is divisible by 3 and divisible by 5
print "FizzBuzz"
else if the integer is divisible by 3
print "Fizz"
else if the integer is divisible by 5
print "Buzz"
else
print the integer
And another implementation in one of the underrated programming languages [1], thanks to some japanese people [2]. And yes, that actually works [3], just tested it in an IDE [4].
>++++++++++[<++++++++++>-]>>>+++>+++++>+<<<<<<
[
>>>+
>- [<<+>>-]<<<+>[<[-]>>>+<<-]<[>>>+++>>[-]<<<<<- +++++++[>++++++++++<-]>.<+++++++[>+++++<-]>.<++++[>++++<-]>+..[-]<]>>
>>- [<<<+>>>-]<<<<+>[<[-]>>>>+<<<-]<[>>>>+++++>[-]<<<<<- +++++++++++[>++++++<-]>.<+++++++[>+++++++<-]>++.+++++..[-]<]>>
>>>
[-
<<<[<+>>>>+<<<-]<[>+<-]>>>>
[
>++++++++++<
[>-[>+>+<<-]>[<+>-] +>[<[-]>-]< [>>+<<<++++++++++>-]<<-]
>---------- >>>[<<<<+>>>>-] <<<<
>>>>>+> >>[-] <[>+<-] <[>+<-] <<<<< [>>>>>+<<<<<+] <
]
>>>>>
[ <++++++[>>++++++++<<-]>> . [-] >[<+>-] >[<+>-] <<<-]
<<<<<
]+
<<<<<
+++++++++++++.---.[-]
<-]
[1] http://en.wikipedia.org/wiki/BrainfuckIn C:
F
Compile with:
gcc -DF='main(){int i;for(i=0;i<101;puts(i++%5?"":"Buzz"))printf(i%3?i%5?"%d":"":"Fizz",i);}' fizzbuzz.c
Not as weird as some entries but here is a rather unusual python version:
a=range(101)
a[0:101:3]=['Fizz']*34
a[0:101:5]=['Buzz']*21
a[0:101:15]=['FizzBuzz']*7
for i in a[1:]: print i
The only real challenge here is turning it in a golf match [1].
Updated. Now 70 characters in Ruby, 8 characters behind Perl:
1.upto(100){|i|a,b=[:Fizz][i%3],[:Buzz][i%5];puts a||b ? "#{a}#{b}":i}
Allowing concatenation (+) for symbols and nil, e.g. (nil + :foo == 'foo', nil + nil == '') would help us a lot. We can monkeypatch Ruby to support this:
class Symbol
def +(other)
to_s + other.to_s
end
end
class NilClass
def +(other)
other.to_s
end
end
Now we're down to 58 characters, not counting the monkeypatch, 4 less than Perl:
1.upto(100){|_|s=[:Fizz][_%3]+[:Buzz][_%5];puts s!=''?s:_}
Updated. I found the best Ruby solution in comp.lang.ruby. 56 characters, but using ?d
for 100
is sinking pretty damn low, IMHO.
1.upto(?d){|i|i%3<1&&x=:Fizz;puts i%5<1?"#{x}Buzz":x||i}
Which language features (that we cannot add by monkeypatching) would make this even shorter?
With these features, fizzbuzz would look like this (46 characters):
1.upto(100){puts [:Fizz][_%3]+[:Buzz][_%5]||_}
@lbrandy [2]: golfscript is very cool. I got fizzbuzz down to 43 characters, but there's definitely room for improvement:
101,(;{\..3%'''Fizz'if\5%'''Buzz'if+\or}%n*
Updated. I've got it down to 37 characters, lbrandy,
building on your solution (which is 40 characters, incidentally). You
can save two characters by replacing <1
by !
,
twice. And another one by creating an 0..99 array and incrementing the
number in the loop, instead of creating a 0..100 array and throwing away
the first element.
100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n*
Amazing what you can do with 36 primitives and 4 datatypes! A new addiction is born.
[1] http://codegolf.com/<!DOCTYPE html>
<html>
<head>
<title>CSS FizzBuzz</title>
<style type="text/css">
body {counter-reset:fb;}
div:before {content:counter(fb);counter-increment:fb;}
div:nth-child(3n+0):before {content:'Fizz';}
div:nth-child(5n+0):before {content:'Buzz';}
div:nth-child(15n+0):before {content:'FizzBuzz';}
</style>
</head>
<body>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
</body>
</html>
<ul>
and <li>
instead of divs, but it's the css that counts. :P - Tor Valamo
My Ook. [1] is a bit rusty, and I don't have a compiler on hand to check it, but I believe this works:
### FizzBuzz in Ook.
Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook?
Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook.
Ook. Ook.
Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook? Ook! Ook! Ook! Ook? Ook? Ook. Ook? Ook.
Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook? Ook? Ook. Ook! Ook? Ook! Ook!
Ook? Ook! Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook.
Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook?
Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook.
Ook? Ook. Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook?
Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook! Ook. Ook! Ook.
Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook! Ook! Ook! Ook? Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook?
Ook. Ook? Ook. Ook? Ook! Ook! Ook? Ook!
Ook? Ook. Ook? Ook. Ook? Ook.
Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook? Ook? Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook!
Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook!
Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook. Ook? Ook.
Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook?
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook.
Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook.
Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook!
Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook?
Ook! Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook!
Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook? Ook. Ook! Ook? Ook. Ook? Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook?
Ook. Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook?
Ook! Ook? Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook. Ook. Ook? Ook! Ook? Ook? Ook.
Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook?
Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook!
Ook! Ook! Ook! Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook? Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook!
Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook? Ook! Ook!
Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook.
Ook. Ook. Ook? Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook.
Ook! Ook! Ook? Ook!
Ook. Ook? Ook. Ook? Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook?
Ook? Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook!
Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook! Ook. Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook.
Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook! Ook?
Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook! Ook? Ook!
[1] http://www.dangermouse.net/esoteric/ook.htmlPlace this in column B and numbers from 1 to 100 in column A
=IF(MOD(A1,15),IF(MOD(A1,5),IF(MOD(A1,3),A1,"Fizz"),"Buzz"),"FizzBuzz")A1
with ROW()
. (Which does make the formula longer, but I'd argue that requiring only one column makes the "solution" shorter.) - Ben Blank
=IF(NOT(MOD(A1;3)); "fizz";"") & IF(NOT(MOD(A1;5)); "buzz";"")
. About writing the numbers in, I assume that you just make a column with A1+1
in A2 and then just copy and paste it to 100. - Yar
=IF(AND(MOD(ROW(),3),MOD(ROW(),5)),ROW(),IF(NOT(MOD(ROW(),3)), "fizz","") & IF(NOT(MOD(ROW(),5)), "buzz",""))
- Nick T
Assuming I were doing this for an interview, I don't think I'd try to show off by cutting down on the number of lines. I'd try to make my answer as clean and simple as possible. In C#,
foreach (int number in Enumerable.Range(1, 100)) {
bool isDivisibleBy3 = (number % 3) == 0;
bool isDivisibleBy5 = (number % 5) == 0;
if (isDivisibleBy3)
Console.Write("Fizz");
if (isDivisibleBy5)
Console.Write("Buzz");
if (!isDivisibleBy3 && !isDivisibleBy5)
Console.Write(number);
Console.WriteLine();
}
Enumerable.Range
to be way overkill. Plain old for (int i = 1; i <= 100; ++i)
is sufficient! - Hosam Aly
Sorry. I couldn't resist.
IDENTIFICATION DIVISION. PROGRAM-ID. FIZZBUZZ. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-FIZZBUZZ-ITEMS. 05 WS-FIZZBUZZ-ITERATION-COUNTER PIC 9(003). 05 WS-FIZZBUZZ-DIVISION. 10 WS-FIZZBUZZ-QUOTIENT PIC 9(003). 10 WS-FIZZBUZZ-REMAINDER PIC 9(003). 05 WS-FIZZ-CHECKS. 10 WS-FIZZ-CHECK PIC X(004) VALUE SPACES. 88 SW-FIZZ-IS-TRUE VALUE "FIZZ". 88 SW-FIZZ-IS-NOT-TRUE VALUE SPACES. 10 WS-BUZZ-CHECK PIC X(004) VALUE SPACES. 88 SW-BUZZ-IS-TRUE VALUE "BUZZ". 88 SW-BUZZ-IS-NOT-TRUE VALUE SPACES. 10 WS-NUMERIC-CHECK PIC X(004) VALUE SPACES. 88 SW-NUMERIC-IS-TRUE VALUE "NUMERIC" 88 SW-NUMERIC-IS-NOT-TRUE VALUE SPACES. 05 WS-FIZZBUZZ-RECORD 10 WS-FIZZBUZZ 15 WS-FIZZ PIC X(004). 15 WS-BUZZ PIC X(004). 10 WS-NUMERIC PIC 9(004). PROCEDURE DIVISION. 0100-PERFORM-FIZZBUZZ. PERFORM VARYING WS-FIZZBUZZ-ITERATION-COUNTER FROM 1 TO 100 BY 1 PERFORM 0150-INITIALIZE-VARIABLES PERFORM 0160-INITIALIZE-SWITCHES PERFORM 0200-CHECK-NUMERIC-FOR-FIZZ PERFORM 0210-WRITE-FIZZ PERFORM 0300-CHECK-NUMERIC-FOR-BUZZ PERFORM 0310-WRITE-BUZZ PERFORM 0400-CHECK-NUMERIC-FOR-NUMERIC PERFORM 0410-WRITE-NUMERIC PERFORM 0500-DISPLAY-RECORD STOP RUN . 0150-INITIALIZE-VARIABLES. MOVE ZEROES TO WS-FIZZBUZZ-ITERATION-COUNTER MOVE ZEROES TO WS-FIZZBUZZ-DIVISION MOVE SPACES TO WS-FIZZ MOVE SPACES TO WS-BUZZ MOVE ZEROES TO WS-NUMERIC . 0160-INITIALIZE-SWITCHES. SET SW-FIZZ-IS-NOT-TRUE TO TRUE SET SW-BUZZ-IS-NOT-TRUE TO TRUE SET SW-NUMERIC-IS-NOT-TRUE TO TRUE . 0200-CHECK-NUMERIC-FOR-FIZZ. DIVIDE WS-FIZZBUZZ-ITERATION-COUNTER BY 5 GIVING WS-FIZZ-QUOTIENT REMAINDER WS-FIZZ-REMAINDER. IF WS-FIZZ-REMAINDER IS EQUAL TO ZERO SET SW-FIZZ-IS-TRUE TO TRUE. END-IF . 0210-WRITE-FIZZ. IF WS-FIZZ-CHECK = "FIZZ" MOVE "FIZZ" TO WS-FIZZ END-IF . 0300-CHECK-NUMERIC-FOR-BUZZ. DIVIDE WS-FIZZBUZZ-ITERATION-COUNTER BY 10 GIVING WS-BUZZ-QUOTIENT REMAINDER WS-BUZZ-REMAINDER. IF WS-FIZZ-REMAINDER IS EQUAL TO ZERO SET SW-BUZZ-IS-TRUE TO TRUE. END-IF . 0310-WRITE-BUZZ. IF WS-BUZZ-CHECK = "BUZZ" MOVE "BUZZ" TO WS-BUZZ END-IF . 0400-CHECK-NUMERIC-FOR-NUMERIC. IF NOT WS-FIZZ IS EQUAL TO "FIZZ" AND NOT WS-BUZZ IS EQUAL TO "BUZZ" SET SW-NUMERIC-IS-TRUE TO TRUE. END-IF . 0410-WRITE-NUMERIC. IF WS-NUMERIC-CHECK = "BUZZ" MOVE WS-FIZZBUZZ-ITERATION-COUNTER TO WS-NUMERIC END-IF . 0500-DISPLAY-RECORD. IF WS-FIZZ IS EQUAL TO "FIZZ" AND WS-BUZZ IS EQUAL TO "BUZZ" DISPLAY WS-FIZZBUZZ BEFORE ADVANCING 1 LINE END-IF IF WS-FIZZ IS EQUAL TO "FIZZ" AND NOT WS-BUZZ IS EQUAL TO "BUZZ" DISPLAY WS-FIZZ BEFORE ADVANCING 1 LINE END-IF IF NOT WS-FIZZ IS EQUAL TO "FIZZ" AND WS-BUZZ IS EQUAL TO "BUZZ" DISPLAY WS-BUZZ BEFORE ADVANCING 1 LINE END-IF IF NOT WS-FIZZ IS EQUAL TO "FIZZ" AND NOT WS-BUZZ IS EQUAL TO "BUZZ" DISPLAY WS-NUMERIC BEFORE ADVANCING 1 LINE END-IF .
WORKING-STORAGE
is referenced somewhere in the PROCEDURE DIVISION
. This is wrong, at least half your WORKING-STORAGE
should be un-referenced wasted space. Same goes for your paragraphs,
there should be a few that are logically unreachable and a few more that
have no reference to them. Finally, every COBOL programmer knows you
need a paragraph called MAINLINE
. Excellent work on the logic errors - every COBOL program needs a few of these too. Overall an A+ - NealB
C# and LINQ? Why not...
Enumerable
.Range(1, 100)
.Select(i =>
i % 15 == 0 ? "FizzBuzz" :
i % 5 == 0 ? "Buzz" :
i % 3 == 0 ? "Fizz" :
i.ToString())
.ToList()
.ForEach(Console.WriteLine);
Enumerable.Range(1, 100).ToList().ForEach(n
=> Console.WriteLine((n % 3 == 0) ? (n % 5 == 0) ? "FizzBuzz" :
"Fizz" : (n % 5 == 0) ? "Buzz" : n.ToString()));
which is almost identical (except it does away with the .Select) and is 2 characters shorter! ;) - CraigTP
Never reinvent the wheel -
import urllib, re
fbregexp = re.compile(".*<pre><code>@echo off([0-9a-zA-Z \n]+)</code></pre>", re.DOTALL)
wf = urllib.urlopen("http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem")
match = fbregexp.match(wf.read())
wf.close()
if match:
print ''.join(match.group(1).split("echo ")).strip()
else:
print "Unable to fetch fizzbuzz data."
Anybody can write a oneliner FizzBuzz, but can you generalize it?
Here's a general FizzBuzz function in Haskell:
fizzBuzz xs = zipWith (\x y -> if null x then show y else x) (f xs)
where f = foldr (zipWith (++) . mask) (cycle [[]])
mask (k, v) = cycle (replicate (k-1) [] ++ [v])
Here's a sample run:
*FizzBuzz> fizzBuzz [(3, "Bucks"), (5, "Fizz"), (7, "Buzz")] [50 .. 150]
["Fizz","Bucks","52","53","Bucks","Fizz","Buzz","Bucks","58","59","BucksFizz","61",
"62","BucksBuzz","64","Fizz","Bucks","67","68","Bucks","FizzBuzz","71","Bucks","73",
"74","BucksFizz","76","Buzz","Bucks","79","Fizz","Bucks","82","83","BucksBuzz",
"Fizz","86","Bucks","88","89","BucksFizz","Buzz","92","Bucks","94","Fizz","Bucks",
"97","Buzz","Bucks","Fizz","101","Bucks","103","104","BucksFizzBuzz","106","107",
"Bucks","109","Fizz","Bucks","Buzz","113","Bucks","Fizz","116","Bucks","118","Buzz",
"BucksFizz","121","122","Bucks","124","Fizz","BucksBuzz","127","128","Bucks","Fizz",
"131","Bucks","Buzz","134","BucksFizz","136","137","Bucks","139","FizzBuzz","Bucks",
"142","143","Bucks","Fizz","146","BucksBuzz","148","149","BucksFizz"]
Code golf it is. Python. 58 characters. No monkey-patching required :P. Woo.
i=0;exec"i+=1;print(i%5<1)*'fizz'+(i%3<1)*'buzz'or i;"*100
edited: to 72
edited: to 58, incorporating an idea from http://stackoverflow.com/questions/437/#2186 (@PabloG, <1 works better than 'not')
From the Perl monks ( modified to take advantage of Perl 5.10's "say" :-)
say+(Fizz)[$_%3].(Buzz)[$_%5]||$_ for 1..100
44 chars.
Here is my solution. It is written in 8051 assembly. You will need a 11.0592 MHz quartz to run this thing :p
;*** CONSTANTS ***
; divider1
; the first divider's value
divider1 equ 3d
;divider2
; the second devider's value
divider2 equ 5d
; limit
; the maximum value that the fizzbizz program can reach. Must be between 0 and 100
limit equ 100d
;*** CODE ***
; Code segment at 0
cseg at 0
ljmp start ; avoir interrupt vectors
org 0x100 ; and go to a safer place
start: ; a.k.a here.
;
mov scon,#0x52 ; set UART to 8,0,n
mov tmod,#0x20 ; Timer1: autoreload
mov th1,#0xfe ; speed: 9600 bps
setb tr1 ; start Timer1
mov dptr,#intro ; load the intro and...
call emit ; beem it!
mov r7,#0 ; set counter to 0
compute:
cjne r7,#limit,continue ; are we finished with counting to 100?
jmp rest_in_peace ; Yes... rest in peace.
continue:
call do_crlf ; go to next line
mov r4,#1 ; set the (r7%3)? flag
inc r7 ; counter++
mov b,#divider1 ;
mov a,r7 ; divide the counter by three
div ab ;
mov a,b ; and get the reminder
jz do_fizz ; if it is null, do a fizz :)
next:
mov b,#divider2 ;
mov a,r7 ; divide the counter by five
div ab ;
mov a,b ; and get the reminder
jz do_buzz ; if it is null, do a buzz :D
mov a,r4 ; did we do a fizz?
jz compute ; if yes, reume the loop
call write_number ; else, write the number
jmp compute ; and resume the loop
rest_in_peace:
clr tr1 ; Stop Timer1
jmp $ ; AM STONED!
; do_fizz
; gets: nothing
; returns: 0 in r4
; description:
; Beems a "Fizz" through the UART
do_fizz:
mov dptr,#fizz ; load the fizz
call emit ; then display it
mov r4,#0 ; and leave a message: "I was here"
jmp next ; then resume your normal activity
; do_buzz
; gets: nothing
; returns: nothing
; description:
; Beems a "Bizz" through the UART
do_buzz:
mov dptr,#buzz ; load the buzz
call emit ; then display it
jmp compute ; then resume the loop
; do_crlf
; gets: nothing
; returns: nothing
; description:
; Beems the Carriage return/Line feed controle caracters through the UART.
do_crlf:
mov dptr,#crlf ; load crlf
call emit ; then send it
ret ; and return
; emit
; gets: the adress of the message to display in dptr
; returns: nothing
; description:
; Beems an ASCIIZ message, stored in the code memory, through the UART.
emit:
mov r6,#0 ; initialize the index to 0
bc_1:
mov a,r6 ;
inc r6 ; load the pointed byte
movc a,@a+dptr ;
jz fin ; if zero then return
jnb ti,$ ; if the last transmission isn't over, stay in your place
mov sbuf,a ; and transmit!
clr ti ; and clear ti to get further notifications :p
jmp bc_1 ; end of the loop
fin:
ret ; return
; emit_id
; gets: the digit's value in A (must be between 0 and 9)
; returns: nothing
; description:
; Translates a one-digit-bcd value located in A into Ascii and the beems it through the
; UART.
emit_id:
mov r5,a
mov a,#'0'
add a,r5
jnb ti,$
mov sbuf,a
clr ti
ret
; write_numer
; gets: the number to display in r7
; returns: nothing
; description:
; Beems the Ascii representation of the number located in r7 through the UART. r7 must
; be between 0 and 99
write_number:
mov a,r7 ;
mov b,#10d ; divide the number by 10
div ab ;
jz write_l ; if it si less than 10 then just write the modulo
call emit_id ; else, write the result (because r7<100) :)
write_l:
mov a,b ; prepare the parameters
call emit_id ; and send the digit
ret ; then return
; *** STATIC DATA ***
; fizz
; type: Asciiz string
; description:
; containes the fizz message
fizz: db "Fizz",0
; buzz
; type: Asciiz string
; description:
; containes the buzz message
buzz: db "Buzz",0
; intro
; type: Asciiz string
; description:
; contains the intro message.
; P.S:
; intro shares it's Asciiz 0 with crlf, 3 code bytes of economy :)
intro: db "The FizzBuzz test"
; crlf:
; type: Asciiz string
; description:
; containes the crlf byte couple
; P.S:
; shares itself and it's Asciiz 0 with intro
crlf: db 10,13,0
; Bye Bye :)
end
Here's the solution in Structured Hebrew (the algorithm language taught in schools in Israel). It's a valid language because I actually wrote a compiler for it once. The following code would actually compile (sans the line numbers, which would be replaced by tabs, which don't work well with right-to-left languages in a left-to-right direction):
1. הכרז על i: שלם
2. עבור i מ-1 עד 100, בצע:
2.1 אם i % 3 = 0 וגם i % 5 = 0 אזי,
2.1.1 הדפס "FizzBuzz"
2.2 אחרת, אם i % 3 = 0 אזי,
2.2.1 הדפס "Fizz"
2.3 אחרת, אם i % 5 = 0, אזי
2.3.1 הדפס "Buzz"
2.4 אחרת,
2.4.1 הדפס i
SO really needs right-to-left support for this kind of stuff :)
All of you people who are checking to see if the number is divisible by three AND that it is divisible by five will find it more concise to consider whether the number is divisible by fifteen. This isn't rocket surgery. And brevity is the soul of wit.
And now for something completely different, a solution in Befunge:
1> :3%#v_"zzif",,,,v
v < <
>:5%#v_"zzub",,,,v
v < <
>::3%\5%*!#v_:. v
v**455:,*48< <
>-#v_@
^ +1<
Give it a try on using this online interpreter [1].
Also, this isn't remotely optimized for space, but that's what the edit button's for. :)
[1] http://www.quirkster.com/js/befunge.htmlMSIL:
.assembly extern mscorlib {}
.assembly fizzbuzz {.ver 1:0:1:0}
.module fizzbuzz.exe
.method static void main() cil managed
{
.entrypoint
.maxstack 2
.locals init (
[0] int32 num,
[1] bool divisibleByThree,
[2] bool divisibleByFive)
//initialize counter
ldc.i4.1
stloc.0
br.s _checkEndCondition
_beginLoop:
//Check divisible by three
ldloc.0
ldc.i4.3
rem
ldc.i4.0
ceq
stloc.1
//Check divisible by five
ldloc.0
ldc.i4.5
rem
ldc.i4.0
ceq
stloc.2
//Check if not divisible by three or five
ldloc.1
brtrue.s _checkDivisibleByThree
ldloc.2
brtrue.s _checkDivisibleByThree
//Not divisible by three or five, write counter
ldloc.0
call void [mscorlib]System.Console::WriteLine(int32)
br.s _incrementCounter
_checkDivisibleByThree:
ldloc.1
brfalse.s _checkDivisibleByFive
ldstr "Fizz"
call void [mscorlib]System.Console::Write(string)
_checkDivisibleByFive:
ldloc.2
brfalse.s _newLine
ldstr "Buzz"
call void [mscorlib]System.Console::Write(string)
_newLine:
call void [mscorlib]System.Console::WriteLine()
_incrementCounter:
ldloc.0
ldc.i4.1
add
stloc.0
_checkEndCondition: ldloc.0
ldc.i4.s 0x65
blt.s _beginLoop
ret
}
while($i++<100)echo(($j=($i%3?"":"Fizz").($i%5?"":"Buzz"))?$j:$i)."
";
PHP, 72 characters. Yes, that is a literal newline.
(many edits happened, didn't track them all!)
Python, using list comprehension and the new x if ... else y
convention.
["FizzBuzz" if (n % 15 == 0) else "Fizz" if (n % 3 == 0) else "Buzz" if (n % 5 == 0) else n for n in range(1,101)]
Obligatory Haskell version.
intToString i | i `mod` 15 = "FizzBuzz"
| i `mod` 3 = "Fizz"
| i `mod` 5 = "Buzz"
| otherwise = show i
main = mapM_ (putStrLn . intToString) [1..100]
i `mod` 15
can't be used as a boolean; you have to say i `mod` 15 == 0
or similar. - Joey Adams
Another python. It won't win the golf match, but it uses the least amount of loops/instructions.
#!C:\Python25\python.exe
print """1\n2\nFizz\n4\nBizz\nFizz\n7\n8\nFizz\nBizz
11\nFizz\n13\n14\nFizzBizz\n16\n17\nFizz\n19\nBizz
Fizz\n22\n23\nFizz\nBizz\n26\nFizz\n28\n29\nFizzBizz
31\n32\nFizz\n34\nBizz\nFizz\n37\n38\nFizz\nBizz
41\nFizz\n43\n44\nFizzBizz\n46\n47\nFizz\n49\nBizz
Fizz\n52\n53\nFizz\nBizz\n56\nFizz\n58\n59\nFizzBizz
61\n62\nFizz\n64\nBizz\nFizz\n67\n68\nFizz\nBizz
71\nFizz\n73\n74\nFizzBizz\n76\n77\nFizz\n79\nBizz
Fizz\n82\n83\nFizz\nBizz\n86\nFizz\n88\n89\nFizzBizz
91\n92\nFizz\n94\nBizz\nFizz\n97\n98\nFizz
"""
Note: this is just for my C practice. I am just thrilled it even works :)
main()
{
int i;
for (i = 1; i <= 100; i++)
{
if (
(i % 3 == 0) && (!(i % 5 == 0))
)
{ printf ("Fizz\n");
continue;
}
else if (
(i % 3 != 0) && (i % 5 == 0 )
)
{ printf ("Buzz\n");
continue;
}
else if (
(i % 3 == 0) && (i % 5 == 0)
)
{ printf ("FizzBuzz\n");
continue;
}
else if (
(!(i % 3 ==0)) && (!(i % 5 == 0))
)
{ printf ("%d\n", i);
continue;
}
}
system("PAUSE");
return 0;
}
Ruby:
require 'rubygems'
require 'fizzbuzz'
puts fizzbuzz
:-D
I know you didn't ask for the shortest, but this is the shortest I know of without rechecking the modulus (in ruby)
100.times do |i|
value = (i % 3 == 0) ? 'Fizz' : '';
value += 'Buzz' if (i % 5 == 0)
puts value.empty? ? i : value;
end
0..(n-1)
; easy fix is to replace 100.times
with 1.upto(100)
. - maerics
Ok, just for grins, here it is in JavaScript:
for(i = 1; i <= 100; i++){
var fizz = (i % 3 == 0);
var buzz = (i % 5 == 0);
var output = "";
//if number is not divisible by 3 or 5, output number
if(!fizz && !buzz){
output = i;
}else{
//if number is divisible by 3, output Fizz
if(fizz){
output = "Fizz";
}
//if number is divisible by 5, add Buzz to output
if(buzz){
output += "Buzz";
}
}
document.write(output + "<br />");
}
There's about a billion different ways to do this...
Way #567,895,670 ("no loops, no ifs" version):
document.write(
new Array(8)
.join("001021001201003")
.substr(0, 100)
.replace(
/\d/g,
function (s, i) {
return [ i + 1, "Fizz", "Buzz", "FizzBuzz" ][s] + "<br/>";
})
);
C#
for(int i=1;i<101;i++)
Console.Write("{0: 0;; }{1:;;Fizz}{2:;;Buzz}",i%3*i%5==0?0:i,i%3,i%5);
92 mandatory characters
C#:
static void Main(string[] args)
{
string[] vals ={"FizzBuzz", "{0}", "{0}", "Fizz", "{0}",
"Buzz", "Fizz", "{0}", "{0}", "Fizz",
"Buzz", "{0}", "Fizz", "{0}", "{0}" };
for (int i = 1; i <= 100; i++)
{
Console.WriteLine(vals[i % 15], i);
}
}
GWBASIC. And Of course, using GOTO statements was mandatory.
10
20 FOR i=1 TO 100
30 IF (i MOD 3 = 0 )AND (i MOD 5 = 0) THEN GOTO 70
40 IF (i MOD 3 = 0 ) THEN GOTO 90
50 IF (i MOD 5 = 0 ) THEN GOTO 110
55 PRINT i
60 GOTO 120
70 PRINT "FizzBuzz"
80 GOTO 120
90 PRINT "Fizz"
100 GOTO 120
110 PRINT "Buzz"
120 NEXT i
Here's how I did it in Groovy (69 chars), but somehow someone did this in 57 chars:
(1..100).each{s=(it%3?"":"fizz")+(it%5?"":"buzz");println s==""?it:s}
C#...
for (int i=1; i<=100; i++)
{
if ((i%3==0) && (i%5==0))
{
Console.WriteLine("FizzBuzz");
}
else if (i%3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i%5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i.ToString());
}
}
When we were interviewing folk for a new position, we used to have candidates walk through this (in the language of their choice, though our shop uses C++) as a bozo filter. I can see that it's now too popular to use this way. ;^)
Occasionally, I'd get someone who claimed to know C++ inside-out, including the libraries. Usually we found some obvious holes. As a lark, I coded up the following FizzBuzz, and asked them to explain how it worked:
//////////////////////////////////////////////////////////////////////
//
// Stream obfuscated FizzBuzz example. Ignores most stream failure
// modes and iword/pword callbacks in the interests of
// brevity/obfuscation.
#include <iostream>
#include <string>
#include <ios>
#define IOS std::ios_base
#include <ostream>
using std::cout;
using std::endl;
using std::ostream;
using std::string;
int getIdx()
{
static const int myIdx = IOS::xalloc();
return myIdx;
}
class FizzBuzzer
{
public:
FizzBuzzer() {};
~FizzBuzzer() {};
ostream &print_on(ostream &os) const;
};
ostream &FizzBuzzer::print_on(ostream &os) const
{
const string fizz("Fizz");
const string buzz("Buzz");
long i = os.iword(getIdx());
void *p = os.pword(getIdx());
if (!p) os << i;
if (reinterpret_cast<long>(p) & 0x02) os << fizz;
if (reinterpret_cast<long>(p) & 0x01) os << buzz;
return os;
}
class FizzBuzzManip
{
public:
explicit FizzBuzzManip(int val) : val_d(val) {};
int divisible3() const { return (val_d % 3) ? 0 : 1; }
int divisible5() const { return (val_d % 5) ? 0 : 1; }
private:
int val_d;
friend ostream &operator<<(ostream &os, const FizzBuzzManip &fz)
{
os.iword(getIdx()) = fz.val_d;
os.pword(getIdx()) = reinterpret_cast<void *>( (fz.divisible3() << 1) | fz.divisible5() );
return os;
}
};
ostream &operator<<(ostream &os, const FizzBuzzer &fz)
{
return fz.print_on(os);
}
int main()
{
FizzBuzzer theFizzBuzz;
for (int i = 1; i <= 100; ++i) {
cout << FizzBuzzManip(i) << theFizzBuzz << endl;
}
}
A short solution, in C:
main(i)
{
for(; i < 101; puts(i++ % 5 ? "" : "Buzz"))
printf(i % 3 ? i % 5 ? "%d" : "" : "Fizz", i);
}
Of course, in C# you should use a simple linq one liner for something like this
string[] fizzBuzz = { "Fizz", "Buzz" };
return String.Join( String.Empty, Enumerable.Range(1, Int32.MaxValue)
.TakeWhile(n => n < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable.Range(1, Int32.MaxValue)
.Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0).Skip(25)
.First()).Select(a => (Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(d => d < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).Where(b => a % b == 0)
.Select(c => fizzBuzz[Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(e => e < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).IndexOf(c)]).Count() == 0) ? a.ToString() : String
.Join( String.Empty, Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(d => d < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).Where(b => a % b == 0)
.Select(c => fizzBuzz[Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(e => e < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).IndexOf(c)]).ToArray())).ToArray());
For anyone wondering what it actually does, here is the basic method without inlining of help methods
String.Join("",
Utility.PositiveNumbers().TakeWhile(n => n < Utility.Primes().Skip(25).First())
.Select(a => (GetFizzBuzzValues(a).Count() == 0) ? a.ToString() : String.Join("", GetFizzBuzzValues(a).ToArray()))
.ToArray());
where GetFizzBuzzValues works like this
public IEnumerable<string> GetFizzBuzzValues(int a){
return GetFizzBuzzValues(a, FirstXUnEvenPrimes(fizzBuzz.Length));
}
public IEnumerable<string> GetFizzBuzzValues(int a,IEnumerable<int> possible){
return possible.Where(b => a % b == 0).Select(c => fizzBuzz[possible.IndexOf(c)]);
}
public IEnumerable<int> FirstXUnEvenPrimes(int x){
return Utility.Primes().Skip(1).TakeWhile(b => b < Utility.Primes().Skip(x+1 ).First());
}
Finally replace Utility.Primes() and Utility.PositiveNumbers with these two rows.
Utility.PositiveNumbers().Where(g => g > 1 && Utility.PositiveNumbers().Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
Enumerable.Range(1, Int32.MaxValue)
A LOLCODE [1] implementation I made for practicing the language, I plan on using it on the qualification round of Google CodeJam:
#!/usr/local/bin/lolcode -f
HAI
CAN HAS STDIO?
IM IN YR LOOP UPPIN YR N WILE DIFFRINT N AN 101
BOTH SAEM N AN 0, O RLY? YA RLY, N R 1, OIC
BOTH SAEM MOD OF N AN 3 AN 0, O RLY?, YA RLY, VISIBLE "FIZZ"!, OIC
BOTH SAEM MOD OF N AN 5 AN 0, O RLY?, YA RLY, VISIBLE "BUZZ"!, OIC
BOTH OF DIFFRINT MOD OF N AN 3 AN 0 AN DIFFRINT MOD OF N AN 5 AN 0
O RLY?
YA RLY, VISIBLE N!
OIC
VISIBLE ""
IM OUTTA YR LOOP
KTHXBYE
[1] http://en.wikipedia.org/wiki/LOLCODEI can think of no reason why you want to, but here's a recursive solution in java:
package j;
public class fizzbuzz {
public static void main(String[] args){
System.out.println(fizzBuzz(100));
}
private static String fizzBuzz(int i) {
String val = null;
if(i==0){
return"";
}
else{
val=fizzBuzz(i-1);
}
if(i%15==0){
return val + " FIZZBUZZ";
}else if(i%3==0){
return val+" FIZZ";
}else if(i%5==0){
return val+" BUZZ";
}
else{
return val+" " +String.valueOf(i);
}
}
}
Also, if I do fizzBuzz(5702) I get a java.lang.StackOverflowError. :-)
Alright, here's an example of a one line python FizzBuzz using a list comprehension. It takes advantage of pure boolean logic in place of any control structure. I did it purely to see if I could.
#!/bin/python
#FizzBuzz with an unpythonic List Comprehension
print [(((not i%3 and not i%5) * 'FizzBuzz') or ((not i%3) * 'Fizz') or ((not i%5) * 'Buzz') or i) for i in range(1,101)]
Can't beat the golf champ but a short c# version (115 chars):
for (int i = 1; i < 101; i++) {Console.WriteLine(((i % 3) + (i % 5) == 0 ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0 ? "Buzz" : i.ToString())))); }
Here's a Delphi/Pascal version:
var
I: Integer;
begin
for I := 1 to 100 do
if (I mod 3 = 0) and (I mod 5 = 0) then
WriteLn('FizzBuzz')
else if I mod 3 = 0 then
WriteLn('Fizz')
else if I mod 5 = 0 then
WriteLn('Buzz')
else
WriteLn(IntToStr(I));
end.
@Michiel de Mare [1]
Which language features (that we cannot add by monkeypatching) would make this even shorter?
At the risk of going a bit off-topic, here are some:
Taken from golfscript [2] which was a language invented precisely for this purpose.
Updated: @Michiel de Mare [3] ... my golfscript version. 39 characters. Programming in this hurts my brain. I'm sure you could do better, though. It works on the same principle as my 58 character python one. Essentially do a n%3<1 and multiply that by fizz (similar for buzz). Add those. And then or the result with the number. So a null string will be replaced by the number.
101,(;{..3%1<'fizz'*\5%1<'buzz'*+\or}%n*
You can see "top" scores for diff. languages here: http://www.shinh.org/p.rb?FizzBuzz. The best golfscript is 37 versus my 39. The best python is 56 vs my 58. And the best ruby is 56 (with no monkey patching :P).
[1] http://stackoverflow.com/questions/437/#453Here's 62 in Perl and I'm not even good at perl. I'm sure Perl golfer could do better.
print"$_\n"for map{($_%3?"":"Fizz").($_%5?"":"Buzz")||$_}1..100
edit: added 1 char to go to 100, not 99
t-sql
select case when rn % 3 = 0 then 'Fizz' else '' end
+ case when rn % 5 = 0 then 'Buzz' else '' end
+ case when rn % 3 > 0 and rn % 5 > 0 then cast(rn as nvarchar) else '' end
from
(
select top 100 row_number() over (order by name) rn
from spt_values
) a
edit- I actually had to write this out on Friday at an interview. Didn't use SQL though. For loops are burned into my head better I guess.
Powershell:
0..100 | %{
if (!($_ % 3)){
if(!($_ % 5)){"FizzBuzz"}
"Fizz"
}elseif(!($_ % 5)){"Buzz"}
else{$_}
}
Here it is in Dataflex. (Why did I get to have to program in the unknown language)
procedure fizzBuzz
integer i
for i from 1 to 100
if (mod(i,15)) eq 0 showln "fizzbuzz"
else if (mod(i,3)) eq 0 showln "fizz"
else if (mod(i,5)) eq 0 showln "buzz"
else showln i
loop
end_procedure
Not the first way I would choose to do it but you could do the following
and now in vb.net... (for a change)
For i As Integer = 1 To 100
Select Case True
Case (i Mod 3 = 0) AndAlso (i Mod 5 = 0)
Console.WriteLine("FizzBuzz")
Case i Mod 3 = 0
Console.WriteLine("Fizz")
Case i Mod 5 = 0
Console.WriteLine("Buzz")
Case Else
Console.WriteLine(i.ToString())
End Select
Next
Obfuscated ColdFusion Script Just for the fun of it. Shoot me or any of my developers if we ever did this.
function d(n){return chr(inputbasen(n,16));}function f(){writeoutput(d('66')&d('69')&d('7a')&d('7a'));}function b(){writeoutput(d('62')&d('75')&d('7a')&d('7a'));}function r(){writeoutput(d('3c')&d('62')&d('72')&d('3e'));}function m(v){h=v mod 3;n=v mod 9;t=v;if(h AND n){writeoutput(v);r();return;}if(not h)f();if(not n)b();r();}for(x=1;x lte 100;x++){m(x);}
Oh, forgot to say I give this test to all my programmer and DBA applicants. and our requirement is mod 3 and mod 9, with a web output. Thus the output of <br> tags. For you CF haters, yes, it's do-able in much smaller code. :P
Scala:
(1 to 100).foreach(x=>println(if (x%15==0)"FizzBuzz"else if (x%3==0)"Fizz"else if (x%5==0)"Buzz"else x))
C++ version without any runtime conditional branches:
#include <iostream>
#include <sstream>
using namespace std;
inline string stringify(int x)
{
ostringstream o;
o << x;
return o.str();
}
template <int N>
struct Enumerator
{
typedef Enumerator<N-1> Prev;
enum {FizzMod = N%3, BuzzMod = N % 5, };
static string FizzBuzz()
{
return Prev::FizzBuzz() + (FizzMod ? string("") : "Fizz") + (BuzzMod ? "" : "Buzz") + ((FizzMod && BuzzMod) ? stringify(N) : "") + "\n";
}
};
template <>
struct Enumerator<0>
{
static string FizzBuzz()
{
return "";
}
};
int main()
{
string fizzBuzz = Enumerator<100>::FizzBuzz();
cout << fizzBuzz;
}
\ FizzBuzz 15:18 07Aug08 ... : FIZZORBUZZ? ( n --- f flag says if a F. or B. happened) ( n -- ) FALSE \ default=no ( n F --- ) OVER \ copy arg ( n F n --- ) 3 /MOD DROP 0 = IF \ divisible by 3 ? ( n F f' --- ) ." Fizz" DROP TRUE THEN ( n T -- ) OVER 5 /MOD DROP 0 = IF \ div by 5? ( n f f' ---) ." Buzz" DROP TRUE THEN ( n f --- ) SWAP DROP ( --- f ) ; : FB 120 0 DO SPACE I FIZZORBUZZ? 0= IF I . THEN LOOP ; FB
Am I the last of my kind?
Sorry to confess:
- I never heard of FizzBuzz until Joel told me about it.
- Aftewards, actually went and did this.
- It's FORTH.
It occurred to me to show this again, but in its more renowned "compressed-write-only-no-comments-no-factoring" version.
: FB 120 0 DO SPACE I FALSE OVER 3 /MOD DROP 0 = IF ." Fizz" DROP TRUE THEN OVER 5 /MOD DROP 0 = IF ." Buzz" DROP TRUE THEN SWAP DROP 0= IF I . THEN LOOP ; FB
Here's another batch file version (requires Windows 2000 or later).
@echo off
setlocal
call :f 1 %%%%i
call :f 3 Fizz
call :f 5 Buzz
call :f 15 FizzBuzz
for /l %%i in (1,1,100) do call echo %%f%%i%%
endlocal
goto :eof
:f
for /l %%i in (%1,%1,100) do set f%%i=%2
goto :eof
I'm truly sorry.
Ah what the heck - here's a C# version using list comprehensions:
(from i in Enumerable.Range(1, 100)
let fizz = i % 3 == 0 ? "Fizz" : null
let buzz = i % 5 == 0 ? "Buzz" : null
let fizzBuzz = fizz + buzz
select fizzBuzz != string.Empty ? fizzBuzz : i.ToString())
.ToList().ForEach(Console.WriteLine);
57 Chars in MUMPS:
F I=1:1:100 S A=I#3,B=I#5 W:A&B I W:'A "Fizz" W:'B "Buzz"
A bit of unrolling and math (Pseudocode):
for i = 1..100
switch i % 15
case 0:
print FizzBuzz
break
case 3:
case 6:
case 9:
case 12:
print Fizz
break
case 5:
case 10:
print Buzz
break
default:
print i
break
C++:
for (int i=1;i<=100;++i)
printf((((i%3)&&(i%5))==0)?"%s%s\n":"%s%s%d\n",((i%3)==0)?"Fizz":"",((i%5)==0)?"Buzz":"",i);
C++ Second Example:
for (int i=0;i<100;printf("%s%s%d\n\0%s%s\n"+!(i%3&&i;%5)*8,!(i%3)?"Fizz":"",!(i%5)?"Buzz":"",i,i++));
Modula-2:
MODULE FizzBuzz;
FORM InOut IMPORT
WriteLine, WriteInt;
VAR
i,m15,m5,m3 : INTEGER;
BEGIN
FOR i := 1 to 100 DO
m15 := i MOD 15;
m5 := i MOD 5;
m3 := i MOD 3;
IF m15 = 0 THEN
WriteLine ( 'FizzBuzz' );
ELSEIF m5 = 0 THEN
WriteLine ( 'Buzz' );
ELSEIF m3 = 0 THEN
WriteLine ( 'Fizz' );
ELSE
WriteInt( i ); WriteLine
END
END
END FizzBuzz.
ADA:
with TEXT_IO;
package int_io is new TEXT_IO.INTEGER_IO( INTEGER);
with TEXT_IO,int_io; use TEXT_IO,int_io;
procudure fizzbuzz is
i,m15,m5,m3 : INTEGER;
begin
for i in INTEGER range 1 .. 100 loop
m15 := i mod 15;
m5 := i mod 5;
m3 := i mod 3;
if m15 = 0 then
PUT ( "FizzBuzz" ); NEW_LINE;
elseif m5 = 0 then
PUT ( "Buzz" ); NEW_LINE;
elseif m3 = 0 then
PUT ( "Fizz" ); NEW_LINE;
else
PUT ( i ); NEW_LINE;
end if;
end loop;
end fizzbuzz;
WinBatch (yeah, I know... but I couldn't pass it up):
@echo off
set _i=1
:loop
set /a _return=%_i% %% 15
if /i "%_return%" EQU "0" (
echo FizzBuzz
goto :doloop)
set /a _return=%_i% %% 5
if /i "%_return%" EQU "0" (
echo Buzz
goto :doloop)
set /a _return=%_i% %% 3
if /i "%_return%" EQU "0" (
echo Fizz
goto :doloop)
echo %_i%
:doloop
set _return=
set /a _i += 1
if /i "%_i%" EQU "101" goto :eof
goto :loop
:eof
I have too much time on my hands :D
In R [1]:
v <- 1 : 100
fizz <- v %% 3 == 0
buzz <- v %% 5 == 0
rest <- !( fizz | buzz )
s <- paste( ifelse( rest, v, "" ),
ifelse( fizz, "Fizz", "" ),
ifelse( buzz, "Buzz", "" ),
sep="" )
cat( s, sep = '\n' )
[1] http://www.r-project.org/Here's an XSLT version. The file has a styelsheet reference to itself, so you can open it in IE and see the output:
fb.xml:
<?xml version="1.0"?>
<!-- Note: The stylesheet reference to the same file!-->
<?xml-stylesheet href="fb.xml" type="text/xsl" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" >
<xsl:output method="html"/>
<xsl:template match="/">
<!-- Start with 1-->
<xsl:apply-templates select="msxsl:node-set( 1 )/text()"/>
</xsl:template>
<!-- Match all text nodes with values <= 100-->
<xsl:template match="text()[ . <= 100 ]">
<xsl:apply-templates select="." mode="print"/>
<br/>
<!-- Recursion! -->
<xsl:apply-templates select="msxsl:node-set( . + 1 )/text()"/>
</xsl:template>
<xsl:template match="text()" mode="print">
<xsl:value-of select="."/>
</xsl:template>
<xsl:template match="text()[ . mod 3 = 0 ]" mode="print">
Fizz
</xsl:template>
<xsl:template match="text()[ . mod 5 = 0 ]" mode="print">
Buzz
</xsl:template>
<!-- Note: the most specific pattern matches first!-->
<xsl:template match="text()[ . mod 3 = 0 ][ . mod 5 = 0 ]" mode="print">
FizzBuzz
</xsl:template>
<!-- No output for the default node() match-->
<xsl:template match="node()"/>
</xsl:stylesheet>
EDIT: No need for two files (.xml and .xslt).
Factor version. Can probably be made cleaner, clearer and shorter, but I'm still a Factor n00b, so...
! Check is a number is divisible by another number
: divisible ( n m -- ? ) mod 0 = ;
! Output a string only if a number is divisible by another and keep the boolean result
: write-if-divisible ( string n m -- ? )
divisible? dup -rot ! Is 'n' divisible by 'm'?
[ write ] [ drop ] if ; ! If yes print string, otheriwse drop it
! Fizzbuzz procedure
: fizzbuzz ( -- )
100 [ ! 100 iterations
1 + dup ! Start at 1 and keep two copies
[ 3 "Fizz" -rot write-if-divisible ] ! Write "Fizz" if divisible by 3
[ 5 "Buzz" -rot write-if-divisible ] bi or ! Write "Buzz" if divisible by 5
[ "" print drop ] [ . ] if ! If divisible by either number print newline otherwise print number
] each ;
Maybe someone can improve this for me?
Didn't see any C++0x + STL solutions, so I decided to ridiculously over-engineer one:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/math/common_factor.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
using namespace std;
using namespace boost;
namespace {
struct FizzBuzzer {
public:
FizzBuzzer() {
typedef pair<int,string> factor_string_t;
const vector<factor_string_t> factor_pairs
= {make_pair(3,"Fizz"), make_pair(5,"Buzz")};
const unsigned int lcm = accumulate(make_transform_iterator(factor_pairs.begin(),bind(&factor_string_t::first,_1)),
make_transform_iterator(factor_pairs.end(), bind(&factor_string_t::first,_1)),
1,
lcm_evaluator());
vec_str_.resize(lcm);
for(auto curr; factor_pairs) {
for(int x = 0; x < lcm; x+=curr.first) {
vec_str_[x]+=curr.second;
}
}
}
string operator()(int i) const {
const string& str = vec_str_[i % vec_str_.size()];
if(str.empty())
return lexical_cast<string>(i);
return str;
}
private:
vector<string> vec_str_;
};
}
int main()
{
transform(counting_iterator<int>(0),
counting_iterator<int>(100),
ostream_iterator<string>(cout, "\n"),
FizzBuzzer());
}
Took me ~25 minutes (also had to look up boost's lcm impl, so that is kinda cheating). And I don't have a compiler capable of handling it yet. Probably shouldn't do this in an interview :)
The obligatory lisp answer:
(loop for x from 1 to 100 do
(format t "~a~%"
(let ((a (cons (= 0 (rem x 3)) (= 0 (rem x 5)))))
(cond
((or (car a) (cdr a))
(format nil "~a~a"
(if (car a) "Foo" "")
(if (cdr a) "Bar" "")))
(T x)))))
WORKING-STORAGE SECTION.
77 FIZZ-NUM PIC 9(01) VALUE 3.
77 BUZZ-NUM PIC 9(01) VALUE 5.
01 WS-FLAGS.
05 FIZZ-FLAG PIC 9(01).
88 PRINT-FIZZ VALUE 0.
05 BUZZ-FLAG PIC 9(01).
88 PRINT-BUZZ VALUE 0.
01 WS-DETAIL-LINE.
05 FILLER PIC X(02).
05 WS-DETAIL-NUMBER PIC ZZ9.
05 FILLER PIC X(03) VALUE ' : '.
05 WS-DETAIL-STRING PIC X(08).
77 I PIC 9(03).
PROCEDURE DIVISION.
0000-MAIN.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 100
MOVE SPACES TO WS-DETAIL-LINE
COMPUTE FIZZ-FLAG = FUNCTION MOD(I, FIZZ-NUM)
COMPUTE BUZZ-FLAG = FUNCTION MOD(I, BUZZ-NUM)
EVALUATE TRUE
WHEN PRINT-FIZZ AND PRINT-BUZZ
MOVE 'FIZZBUZZ' TO WS-DETAIL-STRING
WHEN PRINT-FIZZ
MOVE 'FIZZ' TO WS-DETAIL-STRING
WHEN PRINT-BUZZ
MOVE 'BUZZ' TO WS-DETAIL-STRING
WHEN OTHER
MOVE I TO WS-DETAIL-STRING
END-EVALUATE
MOVE I TO WS-DETAIL-NUMBER
DISPLAY WS-DETAIL-LINE
END-PERFORM.
I decided to try this in COBOL as a learning exercise and a comparative language study. Wouldn't you know it... it is much longer than my solution in C and took me much longer to write, lookin up the COBOL modulus function (thusfar, financial processing hasn't seen a great need for this) and all that.
I changed the spec a bit to also show me the current value of I, just to make things a bit nicer on me when I looked to make sure it worked. (it does)
An F# solution is as follows:-
Edit: Modified to compile under F# 1.9.6.0 latest CTP.
#light let inline (/%) x y = x % y = 0 let fb = function | x when x /% 15 -> "FizzBuzz" | x when x /% 3 -> "Fizz" | x when x /% 5 -> "Buzz" | x -> x.ToString() [1..100] |> List.map (fb >> printfn "%s")
For some reason the context highlighter seems to go crazy with this one so I used pre tags instead!
List.iter
over List.map
unless you really want to produce a new list of 100 copies of unit
- Joel Mueller
Tcl: (assumes $limit is the upper bound you want to count to)
for {set i 0} {$i < $limit} {incr i} {
set str ""
if {$i % 3 == 0} {
append str "FIZZ"
}
if {$i % 5 == 0} {
append str "BUZZ"
}
if {$str == ""} {
append str $i
}
puts $i
}
SQL Server
DECLARE @LoopInt INT
SET @LoopInt =1
WHILE @LoopInt <= 100 BEGIN
PRINT ISNULL(NULLIF(CASE WHEN @LoopInt % 3 = 0 THEN 'Fizz' ELSE '' END
+ CASE WHEN @LoopInt % 5 = 0 THEN 'Buzz' ELSE '' END, ''), @LoopInt)
SET @LoopInt= @LoopInt + 1
END
C++
for(int k=1;k<=100;k++){
if(!(k%3))
cout << "Fizz";
if(!(k%5))
cout << "Buzz";
if((k%3)&&(k%5))
cout << endl << k;
}
Here's a smaller befunge version. 14x7. I would edit Patrick's, but I don't have enough reputation.
1>::3%: #v_v
v,,:,,"fiz">#<
>\5%: #v_v
v,,:,,"buz">#<
>\*! #v_:.v
v5:,*25< <
v>54**-!#@_1+
<h1>The Fizz Problem</h1>
<pre>
<?php
for ($i=1; $i<=100; $i++)
{
$divBy3 = !($i % 3);
$divBy5 = !($i % 5);
if ($divBy3)
{
print "Fizz";
}
if ($divBy5)
{
print "Buzz";
}
else if (!$divBy3)
{
print "$i";
}
print "\n";
}
?>
</pre>
Going golfing... 70 characters in Perl:
for(1..100){print $_%3?($_%5?$_:'Buzz'):($_%5?'Fizz':'FizzBuzz'),"\n"}
Java... takes a command line arg for max value to run until, if not supplied uses 100
package stuff.fizzbuzz;
public class FizzBuzz {
public static void main(String[] args){
int max=100;
if(args.length>1){print("usage: FizzBuzz <maxCount>");System.exit(0);}
if(args.length==1)max = Integer.valueOf(args[0]).intValue();
for(int i=1;i<=max;i++){
boolean modThree = i%3==0;
boolean modFive = i%5==0;
if(modThree)print("Fizz");
if(modFive)print("Buzz");
if(!modThree&&!modFive)print(i);
println();
}
}
private static void print(String s){System.out.print(s);}
private static void print(int i){System.out.print(i);}
private static void println(){System.out.println("");}
}
C++ (first post !)
#include <iostream>
int main (int argc, char* argv[])
{
int threeRem;
int fiveRem;
for (int i = 1; i <= 100; i++)
{
threeRem = i % 3;
fiveRem = i % 5;
if (fiveRem == 0 && threeRem == 0)
std::cout << "FizzBuzz" << std::endl;
else if (threeRem == 0)
std::cout << "Fizz" << std::endl;
else if (fiveRem == 0)
std::cout << "Buzz" << std::endl;
else
std::cout << i << std::endl;
}
return(0);
}
Python, modifying slightly from akdom
print[(((not i%3)*'Fizz')+((not i%5)*'Buzz')) or i for i in range(1,101)]
73 characters and still pritty legible!
print["Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i for i in range(1,101)]
Down to 62 and more legible now (thx @lbrandy)
Since nobody has done anything with a graphing calculator yet, here's my version in TI-BASIC [1]. This was written on a TI-83 Plus graphing calculator which doesn't have a modulus operation built in, hence the use of the fPart function.
:For(X,1,100
:1->A
:If 0=3*fPart(X/3:3->A
:If 0=5*fPart(X/5:5A->A
:If A=1:Disp X
:If A=3:Disp "FIZZ
:If A=5:Disp "BUZZ
:If A=15:Disp "FIZZBUZZ
:End
If I am counting them right, the total symbols should be 93. Note that the TI-83 stores some of the program symbols such as "For(" as a single symbol even though it is displayed as four characters.
[1] http://en.wikipedia.org/wiki/TI-BASICOr, wearing my software manager hat, my solution would be this:
"Hey, Johnny, can I see you for a second?"
:: Johnny enters ::
"Yes?"
"Go solve FizzBuzz for me, wouldja? You can charge the time to code #94921.228."
or, better yet, just enter a bug into FogBugz:
"FizzBuzz implementation is empty"
and assign it to Johnny.
Another JavaScript solution (110 characters) :)
f='Fizz';b='Buzz';for(i=1;i<101;i++){sOut=(i%15==0)?f+b:((i%3==0)?f:((i%5==0)?b:i));document.write(sOut+" ");}
I happened to be using this exercise to learn Lua:
for n=1,100 do
if n%3==0 and n%5==0 then
print("FizzBuzz")
elseif n%3==0 then
print("Fizz")
elseif n%5==0 then
print("Buzz")
else
print(n)
end
end
A C version, that does not use division or modulus:
#include #define FIZZ 3 #define BUZZ 5 #define MAX 100 int main(int argc, char *argv[]) { int i, fizz, buzz; fizz = buzz = 1; for( i = 1; i 0 && buzz > 0) { printf("%d\n",i); } else { if ( fizz == 0) printf("Fizz"); if ( buzz == 0) printf("Buzz"); printf( "\n"); } if (++fizz >= FIZZ) fizz = 0; if (++buzz >= BUZZ) buzz = 0; } return 0; }
This answer isn't perfect in any one dimension, but I like:
I'd love some criticism on this!
for each integer currentNum from 1 to 100 do
if currentNum modulo 15 is 0 then
print 'FizzBuzz'
else if currentNum modulo 5 is 0 then
print 'Buzz'
else if currentNum modulo 3 is 0 then
print 'Fizz'
else
print currentNum
endif
endfor
My Java version:
import static java.lang.System.out;
public class FizzBuzz {
public static void main(String[] args) {
boolean a, b;
for (int i = 1; i <= 100; i++) {
if (a = (i % 3 == 0))
out.print("Fizz");
if (b = (i % 5 == 0))
out.print("Buzz");
if (!a && !b)
out.print(i);
out.println();
}
}
}
@Geocoin: If you're going to say "runtime speed", then say it like you mean it: using endl
(write newline + force flush) is almost certain to make your program
even more I/O-bound than it already is, and makes whatever other
optimisations you have totally irrelevant.
Moral of the story: cout << endl
is not the same as cout << '\n'
. Only use endl
if you actually require your output to be flushed at that point. Here's
an article
[1] by Scott Meyers (author of the Effective C++ series) that says it much better than I can. :-)
In Scheme:
(define (fizz n)
(cond ((= 1 n) `(1))
((= 0 (modulo n 15)) (append (fizz (- n 1)) '("FizzBuzz")))
((= 0 (modulo n 5)) (append (fizz (- n 1)) '("Buzz")))
((= 0 (modulo n 3)) (append (fizz (- n 1)) '("Fizz")))
(else (append (fizz (- n 1)) (list n)))))
(defun fizz (n) ...
, modulo
is called mod
, and instead of else
, t
would be used. Also, usually you would use an apostrophe instead of
backticks for quoting in this case, but I think that both work. - Svante
#!C:\Python25\python.exe
for i in range(1,100):
something = False
text = ""
if not (i%3):
text = text + "Fizz"
something = True
if not (i%5):
text = text + "Buzz"
something = True
if not(something):
print i
else:
print text
That was easy-cheesy...
edit: apparently it's "Buzz", not "Bizz".
Reply to this post [1] here is my generalized version:
(defmacro deffoobar (name start end &rest lists)
"Usage: (deffoobar foo 0 200 '(3 . \"Foo\") '(5 . \"Bar\") '(8 . \"Nak\"))"
(let ((x (intern (format nil "~a" (gensym))))
(i (intern (format nil "~a" (gensym))))
(retnum (intern (format nil "~a" (gensym))))
(retval (intern (format nil "~a" (gensym))))
(istart (if (> start end) end start))
(iend (if (> start end) start end)))
`(defun ,name () ;` //the syntax highlighter is dodgy
(loop for ,x from ,istart to ,iend do
(format t "~a~%"
(let ((,retnum T)
(,retval ""))
(loop for ,i in (list ,@lists) do
(if (zerop (rem ,x (car ,i)))
(progn
(setf ,retnum nil)
(setf ,retval (format nil "~a~a" ,retval (cdr ,i))))))
(if ,retnum ,x ,retval)))))))
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem#65048It's the second batch file version, but it's a little more in the spirit of things:
@echo off
set i=1
:start
call :test %i%
set /a i=%i%+1
if %i%==101 goto :eof
goto :start
:test
set /a modVal3=%1%%3
set /a modVal5=%1%%5
if %modVal3%%modVal5%==00 (
echo FizzBuzz
) else if %modVal3%==0 (
echo Fizz
) else if %modVal5%==0 (
echo Buzz
) else (
echo %1%
)
Here is another C version which avoids divisions and remainders
#include "stdio.h"
int main(int argc, char **argv) {
int i,m15,m3;
for (i=1;i<101;i++) {
m15=i;
m15=(m15 & 15)+(m15>>4);
m15=(m15 & 15)+(m15>>4);
if (m15==15) printf("FizzBuzz\n");
else if (m15==10 || m15==5) printf("Buzz\n");
else {
m3=m15;
m3=(m3 & 3)+(m3>>2);
m3=(m3 & 3)+(m3>>2);
if (m3==3) printf("Fizz\n");
else printf("%d\n",i);
}
}
return 0;
}
It actually works by using the equivalent of 9's remainders in hex (15's remainder?) by adding up the hex digits (theres only 2 digits for numbers under 100). I use that for the divisible by 5 (Buzz) and divisible by 15 (FizzBuzz). I then get the base 4 digit sum to find divisibilty by 3 (Fizz).
In Delphi (complete command-line program):
program fizzbuzz;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
i : integer;
const
c_Start = 1;
c_End = 100;
c_Fizz = 3;
c_Buzz = 5;
c_FizzWord = 'Fizz';
c_BuzzWord = 'Buzz';
begin
for i := c_Start to c_End do begin
if 0=(i mod c_Fizz) then
Write(c_FizzWord);
if 0=(i mod c_Buzz) then
Write(c_BuzzWord);
if (0 < (i mod c_Buzz)) and (0 < (i mod c_Fizz)) then
Write(IntToStr(i));
WriteLn('');
end; //for
end.
Fortran. It has been compiled and run under GNU Fortran, but should work on Fortran 77.
*-------------------------------------------------------------------------------
PROGRAM FIZZBUZZ
*
DO 10 I=1,100
A = MOD(I,3)
B = MOD(I,5)
IF (A.EQ.0.AND.B.EQ.0) THEN
PRINT*, 'fizzbuzz'
ELSEIF (A.EQ.0) THEN
PRINT*, 'fizz'
ELSEIF (B.EQ.0) THEN
PRINT*, 'buzz'
ELSE
PRINT*, I
ENDIF
10 END DO
END
Here it is in 6502 code (BBC Basic Assembler):
10 REM FizzBuzz in 6502 assembler
20 DIM code% 1000
30 OSWRCH = &FFEE
40 OSNEWL = &FFE7
50 work = &70
60 DIM FizzM 4 : $FizzM = "zziF"
70 DIM BuzzM 4 : $BuzzM = "zzuB"
80 FOR pass% = 0 TO 3 STEP 3
90 P%=code%
100 [opt pass%
110
120 .FizzBuzz LDA #1
130 LDX #3
140 LDY #5
150 .FB1 SEC
160 DEX
170 BNE FB2
180 JSR Fizz
190 LDX #3
200 .FB2 DEY
210 BNE FB3
220 JSR Buzz
230 LDY #5
240 .FB3 BCC FB4
250 JSR PrDecimal
260 .FB4 PHA
270 JSR OSNEWL
280 PLA
290 CLC
300 ADC #1
310 CMP #101
320 BCC FB1
330 RTS
340
350 .Fizz PHA
360 LDX #3
370 .Fizz1 LDA FizzM, X
380 JSR OSWRCH
390 DEX
400 BPL Fizz1
410 CLC
420 PLA
430 RTS
440
450 .Buzz PHA
460 LDY #3
470 .Buzz1 LDA BuzzM, Y
480 JSR OSWRCH
490 DEY
500 BPL Buzz1
510 CLC
520 PLA
530 RTS
540
550 .PrDecimal STA work
560 PHA
570 TXA
580 PHA
590 LDA #0
600 PHA
610 .PrDec0 LDX #8
620 LDA #0
630 .PrDec1 ASL work
640 ROL A
650 CMP #10
660 BCC PrDec2
670 SBC #10
680 INC work
690 .PrDec2 DEX
700 BNE PrDec1
710 CLC
720 ADC #ASC"0"
730 PHA
740 LDX work
750 BNE PrDec0
760 .PrDec3 PLA
770 BEQ PrDec4
780 JSR OSWRCH
790 JMP PrDec3
800 .PrDec4 PLA
810 TAX
820 PLA
830 RTS
840 ]
850 NEXT
This is my version in IA-32 assembly. NASM [1] syntax. Linux only.
(NB: This version is deliberately jump-avoidant. For a more jumpy version, see my next version [2].)
Edit: Using similar techniques as mentioned in my other version, I've shaved off 21 bytes from the object code, bringing the size to 114 bytes!
global _start
section .text
_start sub eax, 104
sub ebx, 99
lea esp, [esp + 4*eax]
mov edi, esp
push dword 0x7a7a7542 ; Buzz
push dword 0x7a7a6946 ; Fizz
mov edx, esp
.loop lea ecx, [ebx + 100]
mov eax, ecx
aam 3
mov eax, ecx
setz ch
aam 5
setz cl
jecxz .num
and cl, ch
xor ch, 1
inc cl
movzx esi, ch
movzx ecx, cl
lea esi, [edx + 4*esi]
rep movsd
jmp .nl
.num lea eax, [ebx + 100]
aam
xchg al, ah
test al, al
setz cl
add ax, 0x3030
push eax
lea esi, [edx + ecx - 4]
xor cl, 1
inc ecx
rep movsb
pop eax
.nl mov al, 10
stosb
inc ebx
jle .loop
lea eax, [ebx + 3]
sub edi, edx
lea ecx, [edx + 8]
lea edx, [edi - 8]
int 0x80
mov eax, ebx
dec ebx
int 0x80
To build, use:
nasm -Ox -f elf fizzbuzz.asm
ld -s -m elf_i386 fizzbuzz.o
[1] http://nasm.sourceforge.net/This is a much more jump-happy version of
my last submission
[1]. On the upside, the object code size is reduced by 14 bytes, mostly by using lea
(3 bytes) instead of constant register moves (5 bytes). (e.g., mov edx, 5
gets translated into lea edx, [ebx + 4]
, with the understanding that ebx
is always fixed at 1.)
Edit: Since posting this initially, I've shaved off another 13 bytes,
resulting in 108 bytes of object code, by exploiting that most
registers start at 0, edx
's top bits are never set, and [edi]
< [ebp]
< [esp + 4]
in code size.
Edit2: By buffering all output into the stack before writing, I've
shaved off another 8 bytes, resulting in 100 bytes of object code.
(Bonus: apart from the Fizz/Buzz pushing, all instructions are 3 bytes
or less.) I can cut another 3 bytes by buffering to .bss
instead of the stack, but using additional sections adds bulk to the executable elsewhere, resulting in a net disadvantage.
global _start
section .text
_start sub eax, 104
sub ebx, 99
push dword 0x7a7a7542 ; Buzz
push dword 0x7a7a6946 ; Fizz
mov esi, esp
lea esp, [esi + 4*eax]
mov edi, esp
push edi
.loop lea ecx, [ebx + 100]
mov eax, ecx
aam 15
jz .fiftn
mov eax, ecx
aam 5
jz .five
mov eax, ecx
aam 3
jz .three
mov eax, ecx
aam
add al, 0x30
test ah, ah
jz .onedig
xchg ah, al
add al, 0x30
stosb
xchg ah, al
.onedig stosb
jmp .nl
.three mov eax, [esi]
stosd
jmp .nl
.fiftn mov eax, [esi]
stosd
.five mov eax, [esi + 4]
stosd
jmp .nl
.nl mov al, 10
stosb
inc ebx
jle .loop
pop ecx
mov edx, edi
sub edx, ecx
lea eax, [ebx + 3]
int 0x80
mov eax, ebx
dec ebx
int 0x80
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/37420#37420WITH Nbrs(n) AS (
SELECT 1
UNION ALL
SELECT 1 + n FROM Nbrs WHERE n < 100)
SELECT CASE WHEN n%5=0 AND n%3=0 THEN 'BizzBuzz'
WHEN n%3 = 0 THEN 'Bizz'
WHEN n%5 = 0 THEN 'Buzz'
ELSE CAST(n AS VARCHAR(8))
END
FROM Nbrs
OPTION (MAXRECURSION 100);
That's my version in C++, coded in less than 2 minutes and without any test-run before completion. Does that prove I am a good programmer? Certainly not. It just shows that I can solve FizzBuzz in less than 2 minutes. Anyone who can do it in 1 minute (without preliminary thinking, of course)?
This code is exactly the first version I wrote, thus being the first solution that came to my mind. It was not improved or revised afterwards. Maybe "first version contests" could show something about someone's way of thinking.
/* first version, not improved or revised */
#include <iostream>
int main() {
bool f;
for (int i = 1; i <= 100; i++) {
f = false;
if (i % 3 == 0) {
std::cout << "Fizz";
f = true;
}
if (i % 5 == 0) {
std::cout << "Buzz";
f = true;
}
if (!f)
std::cout << i;
std::cout << std::endl;
}
return 0;
}
Simple, easy answer in python:
for x in range(1, 101):
s = ''
if not x % 3:
s = 'Fizz'
if not x % 5:
s += 'Buzz'
print s if len(s) else x
PHP, 85 symbols:
while($i<100){$i++;echo($i%15)?($i%3)?($i%5)?$i."\n":"buzz\n":"fizz\n":"fizzbuzz\n";}
In Ocaml [1].
let rec fizzbuzz p =
begin
match p mod 3, p mod 5 with
| 0,0 -> print_string "FizzBuzz"
| 0, _ -> print_string "Fizz"
| _, 0 -> print_string "Buzz"
| _,_ -> print_int p;
end;
print_newline();
if p < 100 then fizzbuzz (p+1);
in fizzbuzz 1;;
[1] http://caml.inria.fr/ocaml/index.en.htmlC# 3.5 Code generation with CodeDom : 1 statement
using System.CodeDom;
public class FizzBuzz
{
static void Main(string[] args)
{
new CSharpCodeProvider().CompileAssemblyFromDom(new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true,
}, new CodeCompileUnit()
{
Namespaces = {
new CodeNamespace()
{
Name = "FizzBuzzerNameSpace" ,
Types = {
new CodeTypeDeclaration("FizzBuzzer")
{
Members = {
new CodeMemberMethod()
{
Name="Run",
Attributes = MemberAttributes.Static | MemberAttributes.Public,
Statements = {
new CodeIterationStatement(
new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i", new CodePrimitiveExpression(0)),
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(100)),
new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))),
new CodeConditionStatement(
new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0))),
new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("FizzBuzz")))
)
{
FalseStatements = {
new CodeConditionStatement(
new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)),
new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Fizz")))
)
{
FalseStatements = {
new CodeConditionStatement(
new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)),
new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Buzz")))
)
{
FalseStatements = {
new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodeVariableReferenceExpression("i"))
}
}
}
}
}
}
)
}
}
}
}
}
}
}
}).CompiledAssembly.GetType("FizzBuzzerNameSpace.FizzBuzzer").GetMethod("Run").Invoke(null, new object[0] { });
}
}
C# 3.5 Code generation with CodeDom multi statement version :
using System.CodeDom;
public class FizzBuzz
{
static void Main(string[] args)
{
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace ns = new CodeNamespace();
ns.Name = "FizzBuzzerNameSpace";
unit.Namespaces.Add(ns);
CodeTypeDeclaration fizzBuzzer = new CodeTypeDeclaration("FizzBuzzer");
ns.Types.Add(fizzBuzzer);
CodeMemberMethod run = new CodeMemberMethod();
run.Attributes = MemberAttributes.Static | MemberAttributes.Public;
run.Name = "Run";
fizzBuzzer.Members.Add(run);
CodeIterationStatement forLoop = new CodeIterationStatement();
forLoop.InitStatement = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i", new CodePrimitiveExpression(0));
forLoop.IncrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1)));
forLoop.TestExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(100));
CodeBinaryOperatorExpression fizzBuzzCondExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)));
var invokeFizzBuzz = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("FizzBuzz")));
CodeConditionStatement fizzBuzzIf = new CodeConditionStatement(fizzBuzzCondExpression, invokeFizzBuzz);
CodeBinaryOperatorExpression fizzCondExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0));
var invokeFizz = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Fizz")));
CodeConditionStatement fizzIf = new CodeConditionStatement(fizzCondExpression, invokeFizz);
fizzBuzzIf.FalseStatements.Add(fizzIf);
CodeBinaryOperatorExpression buzzCondExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0));
var invokeBuzz = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Buzz")));
CodeConditionStatement buzzIf = new CodeConditionStatement(buzzCondExpression, invokeBuzz);
fizzIf.FalseStatements.Add(buzzIf);
buzzIf.FalseStatements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodeVariableReferenceExpression("i")));
forLoop.Statements.Add(fizzBuzzIf);
run.Statements.Add(forLoop);
CSharpCodeProvider prov = new CSharpCodeProvider();
var result = prov.CompileAssemblyFromDom(new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true,
}, unit);
result.CompiledAssembly.GetType("FizzBuzzerNameSpace.FizzBuzzer").GetMethod("Run").Invoke(null, new object[0] { });
Console.Read();
}
}
My attempt in Java, it seems to work!
package Fun;
public class FizzBuzz {
public static void main(String[] args) {
for(int i = 1; i <= 100; i++) {
if((i%3 == 0 || (i%5) == 0)) {
if((i%3) == 0) System.out.print("Fizz");
if((i%5) == 0) System.out.print("Buzz");
}
else { System.out.println(i); }
System.out.println();
}
}
}
T-SQL
WITH Numbers(Number) AS (
SELECT 1
UNION ALL
SELECT Number + 1
FROM Numbers
WHERE Number < 100
)
SELECT
CASE
WHEN Number % 3 = 0 AND Number % 5 = 0 THEN 'FizBuzz'
WHEN Number % 3 = 0 THEN 'Fizz'
WHEN Number % 5 = 0 THEN 'Buzz'
ELSE CONVERT(VARCHAR(3), Number)
END
FROM Numbers
ORDER BY Number
Erlang
-module(fizzbuzz).
-export([start/0]).
start() ->
fizzbuzz(1).
fizzbuzz(100) ->
true;
fizzbuzz(X) when (X rem 5 == 0), (X rem 3 == 0) ->
io:format("FizzBuzz~n", []),
fizzbuzz(X+1);
fizzbuzz(X) when X rem 3 == 0 ->
io:format("Fizz~n", []),
fizzbuzz(X+1);
fizzbuzz(X) when X rem 5 == 0 ->
io:format("Buzz~n", []),
fizzbuzz(X+1);
fizzbuzz(X) ->
io:format("~p~n", [X]),
fizzbuzz(X+1).
Not really amazing that the switch version is the fastest...
// 2,6 microseconds
private static void FizzBuzz2()
{
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
;//Console.WriteLine("FizzBuzz");
else
if (i % 3 == 0)
;//Console.WriteLine("Fizz");
else
if (i % 5 == 0)
;//Console.WriteLine("Buzz");
else
;// Console.WriteLine(i);
}
}
// 1,6 microseconds
private static void FizzBuzz3()
{
for (int i = 0; i <= 100; i++)
{
switch ((i % 3 == 0 ? 0 : 1) + (i % 5 == 0 ? 0 : 2))
{
case 0: ;/*Console.WriteLine("FizzBuzz");*/ break;
case 1: ;/*Console.WriteLine("Fizz");*/ break;
case 2: ;/*Console.WriteLine("Buzz");*/ break;
case 3: ;/*Console.WriteLine(i);*/ break;
}
}
}
// 2,1 microseconds
private static void FizzBuzz4()
{
int i;
for (i = 1; i <= 100; i++)
{
switch (i % 15)
{
case 0: ;/* Console.WriteLine("FizzBuzz");*/ break;
case 3:
case 6:
case 9:
case 12: ;/*Console.WriteLine("Fizz");*/ break;
case 5:
case 10: ;/*Console.WriteLine("Buzz");*/ break;
default: ;/*Console.WriteLine(i);*/ break;
}
}
}
// 11 microseconds
private static void FizzBuzz1()
{
bool b;
string s;
for (int i = 1; i <= 100; i++)
{
b = false;
if (i % 3 == 0)
{
;// Console.Write("Fizz");
b = true;
}
if (i % 5 == 0)
{
;// Console.Write("Buzz");
b = true;
}
s = b ? string.Empty : i.ToString();
;//Console.WriteLine(s);
}
}
WebMethods Flow.
To be fair, WM lets you write services in Java, but I challenged myself to do FizzBuzz in their Flow doodleware, and to only use the available built-in services.
I couldn't find a built in modulus operator, so rather than dividing, multiplying then comparing with the original, I used three counters.
"Unfortunately" you can't see all of the logic - you'd have to click around the UI to see where everything is hidden.
Oracle SQL
select decode(mod(level,3),0, decode(mod(level,5),0,'fizzbuzz','fizz'),
decode(mod(level,5),0,'buzz',level))
from dual
connect by level <= 100
/
A short, efficient and easier to read Ruby version.
#!/usr/bin/env ruby
1.upto(100) do |i|
print "Fizz" if (i % 3).zero? and (divisible = true)
print "Buzz" if (i % 5).zero? and (divisible = true)
print i if not divisible
print "\n"
end
(divisible = true) is actually an assignment which always returns 'True'. Due to the boolean logic of 'AND', interpreter always evaluates this expression if mod result is 0 (zero), thus resulting an assignment. If mod operation result is non-zero, this expression is never evaluated due to the "boolean shortcut" optimization.
T-SQL with no predefined tables. Maybe a little verbose!
DECLARE @n AS INT, @m AS INT;
SET @n=1; SET @m=100;
WITH ntom(n) AS(SELECT @n AS n UNION ALL SELECT n+1 FROM ntom WHERE n<@m),
fb AS (SELECT (n%3) AS mod3, (n%5) AS mod5, n FROM ntom)
SELECT CASE WHEN mod3 = 0 AND mod5 = 0 THEN 'FizzBuzz'
WHEN mod3 = 0 THEN 'Fizz' WHEN mod5 = 0 THEN 'Buzz'
ELSE CAST(n AS VARCHAR(10)) END AS fizzbuzz FROM fb;
In OCaml [1]:
let fb (i:int) : string = match (i mod 3, i mod 5) with
(0,0)->"FizzBuzz"
| (0,_)->"Fizz"
| (_,0)->"Buzz"
| _ ->string_of_int i
in let rec mklist (n:int):int list =
if n=0 then [] else n::(mklist (n-1))
in (for i=0 to 100 do print_endline (fb i) done;
List.rev_map fb (mklist 100));;
The for loop prints everything out, but isn't purely functional, so I added mklist and the List.rev_map statement which evaluates to a list containing the correct output of the problem. If anyone knows a better way to do this functionally, please let me know.
[1] http://caml.inria.fr/Can be run in a browser via the Groovy web console [1]
1.upto 100, {println !(it % 15) ? "fizzbuzz" : !(it % 3) ? "fizz" : !(it % 5) ? "buzz" : it}
A more readable version is:
1.upto 100, {
def fizz = it % 3 == 0
def buzz = it % 5 == 0
println fizz && buzz ? "fizzbuzz" : fizz ? "fizz" : buzz ? "buzz" : it
}
[1] http://groovyconsole.appspot.com/C# 4 version. I particularly like this because it is so easy to add new rules (e.g. modulo 7 = "Bang")
void FizzBuzz()
{
var rules = new[]
{
new { Name = "Fizz", Modulus = 3 },
new { Name = "Buzz", Modulus = 5 },
};
Enumerable.Range(1, 100).Select(i => i.ToString()).Zip
(
rules.Select(r => CreateSequence(r.Modulus, r.Name))
.Aggregate((f, b) => f.Zip(b, (x, y) => x + y)),
(i, s) => String.IsNullOrEmpty(s) ? i : s
)
.ToList().ForEach(Console.WriteLine);
}
private static IEnumerable<string> CreateSequence(int modulus, string name)
{
while (true)
{
for (int i = 1; i < modulus; ++i)
yield return null;
yield return name;
}
}
Scala:
object FizzBuzz {
def main(args: Array[String]): Unit = {
for(i <- 1 to 100) {
println(
(i % 3, i % 5) match {
case(0, 0) => "FizzBuzz"
case(0, _) => "Fizz"
case(_, 0) => "Buzz"
case _ => i
}
)
}
}
}
My favorite ...
for i = 1 to 100
select case i
case 1
debug.print i
case 2
debug.print i
case 3
debug.print "fizz"
case 4
debug.print i
case 5
debug.print "buzz"
case 6
debug.print "fizz"
case 7
debug.print i
case 8
debug.print i
case 9
debug.print "fizz"
case 10
debug.print "buzz"
case 11
debug.print i
case 12
debug.print "fizz"
case 13
debug.print i
case 14
debug.print i
case 15
debug.print "fizzbuzz"
...
...
end select
next i
Some simple python, generalized. Opinions are welcome.
in our simple case you call q(1,100,'fizz'=3,'buzz'=5)
def q(a, b, **c):
for i in range(a, b+1):
d = ''
for j in c:
if i % c[j] < 1: d += j
print d or i
A JavaScript one-liner (60 characters):
for(i=1;i<101;i++)alert((i%3?"":"Fizz")+(i%5?"":"Buzz")||i)
Explanation:
for(i=1;i<101;i++) // Loop for i=1 to i=100
alert( // Output to the user
(i%3)?"":"Fizz")+ // If i%3!=0 then "" otherwise "Fizz"
(i%5)?"":"Buzz") // If i%5!=0 then "" otherwise "Buzz"
||i) // If left side is falsy return i
Note: An empty string in Javascript is treated as false when used as a boolean.
And another one using an Array to loop:
for(i in new Array(100).join(0).split(0))alert(((++i)%3?"":"Fizz")+(i%5?"":"Buzz")||i)
Compressed Python weighing in at 228 bytes, which is more than half as small as Grant’s [1]:
print '''
eJxNzbsNxDAMA9Ce2+hjfdoU2eUGuCbT52ALOFamKRBPoLg/zwPH9f09OyfqhF2JnI8YxHc8dUBy
Lk1jVajRXGP6gvZ/bgIb2ti2hLHuo7vBSfeAj+6sL8VifY2+Cov0EMTowXokgvUcPQ1JegZy9GS9
FMV6jV6FIr0FPXqz3ok++gufUm5s'''.decode('base64').decode('zlib')
[1] http://stackoverflow.com/questions/584No template abuse?
template<int I, bool mod3 = (I % 3) == 0, bool mod5 = (I % 5) == 0> struct FizzBuzz {
static const std::string lolcakes = std::string(1, I + '0') + "\n" + FizzBuzz<I + 1>::lolcakes;
};
template<bool mod3, bool mod5> struct FizzBuzz<100, mod3, mod5> {
static const std::string lolcakes = "";
};
template<int I, bool mod5> struct FizzBuzz<I, true, mod5> {
static const std::string lolcakes = "Fizz\n" + FizzBuzz<I + 1>::lolcakes;
};
template<int I, bool mod3> struct FizzBuzz<I, mod3, true> {
static const std::string lolcakes = "Buzz\n" + FizzBuzz<I + 1>::lolcakes;
};
template<int I> struct FizzBuzz<I, true, true> {
static const std::string lolcakes = "FizzBuzz\n" + FizzBuzz<I + 1>::lolcakes;
};
std::cout << FizzBuzz<0>::lolcakes;
On reflection, this probably won't compute FizzBuzz at compile time. But it would do if C++ could mutate strings at compile-time in a defined fashion.
The shortest Python golf i can come up with (and I haven't seen any shorter w/o the use of eval
):
for n in range(1,101):print'FizzBuzz'[n%3and 4:n%5and 4or 8]or n
Please let me know (by comment) if you know of any shorter.
Oracle SQL seems a bit under-represented. Here's a take on it in Oracle, avoiding fancy loops and keeping it to basic selects:
select decode(output, null, cast(r as varchar(3)), output) result
from (Select Rownum r,
decode(mod(rownum, 3), 0, 'Fizz') ||
decode(mod(rownum, 5), 0, 'Buzz') as output
From dual
Connect By Rownum <= 100)a
order by r;
Or another possible solution, requiring more evaluations but no nested selects:
Select case when mod(rownum, 3) <> 0 and mod(rownum, 5) <> 0 then cast(rownum as varchar(3))
else (decode(mod(rownum, 3), 0, 'Fizz')
|| decode(mod(rownum, 5), 0, 'Buzz'))
end as output
From dual
Connect By Rownum <= 100;
And another T-SQL variation, this one has some close similarities to other posts here. The idea on this one was to avoid using declared variables or any existing data tables.
--first we create our temporary test data set using a CTE or Common Table Expression
with testdata (counter) as
(
select 1
union all
select counter +1
from testdata
where (counter + 1) <= 100
)
--next we run against the CTE to generate the FizzBuzz answers
select
case when counter % 3 = 0 or counter % 5 = 0 then
case when counter % 15 = 0 then 'FizzBuzz' else
case when counter % 3 = 0 then 'Fizz' else
case when counter % 5 = 0 then 'Buzz'
end
end
end
else cast(counter as char) end as FizzBuzz
from testdata
Javascript (66 characters):
for(var i=1;i<101;i++){alert((i%3?"":"fizz")+(i%5?"":"buzz")||i)};
Warning: Switch alert() to console.log() unless you've got a lot of time to spare
because golf and J [1] are fun:
> (((0 = 3 | ]) + 2 * 0 = 5 | ]) { ('Fizz'([ ; ] ; ,)'Buzz') ;~ ":)"0 >: i.100
55 characters with spaces removed, although I'm sure there's room for improvement.
(((0 = 3 | ]) + 2 * 0 = 5 | ]) { ('Fizz'([ ; ] ; ,)'Buzz') ;~ ])"0 >: i.100
53 if you don't mind boxed format
[1] http://jsoftware.comSurely all that division has to be a massive performance bottleneck!
Much better to use multiplication to work out the fizz and buzz in advance.
int next_fizz = 3;
int next_buzz = 5;
for (int i = 1; i <= 100; i++)
{
if (i != next_fizz && i != next_buzz)
{
printf("%d\r\n", i);
}
else
{
if (i == next_fizz)
{
printf("fizz");
next_fizz += 3;
}
if (i == next_buzz)
{
printf("buzz");
next_buzz += 5;
}
printf("\r\n");
}
}
Ok, here is a C# lambda extensible fizzbuzz! I was actually asked this in an interview today and I provided a crappy solution. So now here is a good one.
public static void FizzBuzz()
{
Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");
var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);
output.ToList().ForEach(x => Console.Write(x));
}
Clojure. Golfing: 168 chars.
(defn $([n]($ 1 n))([n t](let[f(=(mod n 3)0)b(=(mod n 5)0)](if(<= n t)(do(if
f(print "Fizz"))(if b(print "Buzz"))(if(not(or f b))(print
n))(newline)(recur(inc n)t))))))
To be called as such: ($ n)
And now legible:
(defn fizzbuzz
([n] (fizzbuzz 1 n))
([n top]
(let [fizz (=(mod n 3)0)
buzz (=(mod n 5)0)]
(if (<= n top)
(do
(if fizz
(print "Fizz"))
(if buzz
(print "Buzz"))
(if (not (or fizz buzz))
(print n))
(newline)
(recur (inc n) top))))))
To be called like so: (fizzbuzz n)
Could probably be shorter, but I'm still learning the language.
Mathematica: (85 characters)
Scan[Print@Switch[Mod[#,15],0,"FizzBuzz",3|6|9|12,"Fizz",5|10,"Buzz",_,#]&,Range@100]
Perl, using regular expressions rather than aritmetic:
$output = join(" ",1 .. 100);
$output =~ s/((\S+ ){2})\S+/$1Fizz/g;
$output =~ s/((\S+ ){4})\S+/$1Buzz/g;
$output =~ s/((\S+ ){14})\S+/$1FizzBuzz/g;
print $output;
In Common Lisp a straightforward iterative solution would be:
(loop for i from 1 to 100 do
(cond ((zerop (mod i 15)) (format t "FizzBuzz "))
((zerop (mod i 3)) (format t "Fizz "))
((zerop (mod i 5)) (format t "Buzz "))
(t (format t "~A " i))))
But it's common to think of a recursive solution when programming in Common Lisp, and so an easy one - although not very efficient - would be:
(defun fizzbuzz (i)
(unless (zerop i)
(append (fizzbuzz (1- i))
(list (cond ((zerop (mod i 15)) 'FizzBuzz)
((zerop (mod i 3)) 'Fizz)
((zerop (mod i 5)) 'Buzz)
(t i))))))
(fizzbuzz 100)
That version could easily blow the stack, a better version would be a tail recursive one, which carries the result through the recursive calls:
(defun fizzbuzz-tail-recursive (i)
(fb-recursive i '()))
(defun fb-recursive (x result)
(if (zerop x)
result
(fb-recursive (1- x)
(cons (cond ((zerop (mod x 15)) 'FizzBuzz)
((zerop (mod x 3)) 'Fizz)
((zerop (mod x 5)) 'Buzz)
(t x))
result))))
(fizzbuzz-tail-recursive 100)
Which is also way a lot faster than the non-tail-recursive version.
[25]> (time (progn (fizzbuzz 7000) nil))
Real time: 3.255142 sec.
Run time: 3.146522 sec.
Space: 196028000 Bytes
GC: 361, GC time: 1.831725 sec.
NIL
[26]> (time (progn (fizzbuzz-tail-recursive 7000) nil))
Real time: 0.003486 sec.
Run time: 0.002999 sec.
Space: 56000 Bytes
NIL
And with a call to fizzbuzz
with 1 million:
[52]> (time (progn (fizzbuzz 1000000) nil))
*** - Program stack overflow. RESET
Real time: 0.010824 sec.
Run time: 0.010998 sec.
Space: 0 Bytes
[53]> (time (progn (fizzbuzz-tail-recursive 1000000) nil))
Real time: 1.200375 sec.
Run time: 1.095833 sec.
Space: 8000000 Bytes
GC: 8, GC time: 0.230964 sec.
NIL
Here is a one liner in Lua (88 characters):
for i=1,100 do print(i%15==0 and"FizzBuzz"or i%3==0 and"Fizz"or i%5==0 and"Buzz"or i)end
(EDIT) And here is the generalized version:
function f(t) for i=t.s,t.e do r="" for _,v in ipairs(t) do r=r..(i%v[1]==0 and v[2] or "") end print(#r==0 and i or r) end end
f{s=1,e=100,{3,"Fizz"},{5,"Buzz"}}
Perl, 58 chars. No need for any option or feature:
print$_%15?$_%3?$_%5?$_:Buzz:Fizz:FizzBuzz,"\n"for(1..100)
Another revised version (57 chars):
print$_%15?$_%3?$_%5?$_:Buzz:Fizz:FizzBuzz,'
'for(1..100)
The student's choice: CASIO fx-9750G Plus...
For 1->F To 100
F/3=Int(F/3) And F/5!=Int(F/5)=>"FIZZ"
F/5=Int(F/5) And F/3!=Int(F/3)=>"BUZZ"
F/15=Int(F/15)=>"FIZZBUZZ"
F/3!=Int(F/3) And F/5!=Int(F/5)=>F.
Next
Where .
is output (disp), /
is division, !=
is not equal, ->
is variable assignation, and =>
is shorthand if.
EDIT:
The above solution is 139 bytes, but it can be optimized to 122 bytes:
For 1->T To 100
If T/15=Int(F/15)
Then "FIZZBUZZ"
Next
IfEnd
If T/3=Int(F/3)
Then "FIZZ"
Next
IfEnd
If T/5=Int(F/5)
Then "BUZZ"
Next
IfEnd
T.
Next
Although this solution seems longer, it contains less instructions and is overall 17 bytes smaller than the previous one.
EDIT 2:
Using a slightly different technique, the program can be even further shortened:
For 1->X To 100
ClrText
" ".
Locate 1,1,X
X/5=Int(X/5)=>Locate 1,1," BUZZ"
X/3=Int(X/3)=>Locate 1,1,"FIZZ"
" ".
Next
This version is only 101 bytes long.
EDIT 3:
The program above was still not the best I could do, but the version below sure is:
For 1->X To 10^2
ClrText
Locate 5,1,X
X/3->A
X/5->B
A=Int A=>"FIZZ"
B=Int B=>Locate 5,1,"BUZZ"
Next
Here, 10^
is one symbol. This is the final version: 82 bytes.
In Haskell:
import Control.Monad.State
import Control.Monad.Trans
import Control.Monad.Writer
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"
main = putStr $ execWriter $ mapM_ (flip execStateT True . fizzbuzz) [1..100]
C#
Console.WriteLine(string.Join(", ", Enumerable.Range(1, 100).Select<int, string>(
(number) => number % 15 == 0 ? "Fizz Buzz" : number % 3 == 0
? "Fizz" : number % 5 == 0 ? "Buzz" : number.ToString()).ToArray()));
One of many possible answers in J:
fb=: 3 : '(#. 0 = 3 5|y) { (": y); ''buzz'' ; ''fizz''; ''fizzbuzz'''
fb"0 1+i.100
This one is nice because it's actually readable (and not hardcoded to 100).
More criptic:
fb2 =: 3 : '(<"1 (i. y),.{:&bx"1 [ 0 = 1 3 5 15 |"_ 0 [1+i.y) { (,.":&.>1+i.y),"1 ''fizz'';''buzz'';''fizzbuzz'''
fb2 100
I'm too lazy at the moment to code a version that concatenates 'fizz' and 'buzz' for multiples of 15...
Best golf I could do in PHP (81 chars):
for($a=0;$a<101;$a++){
$b=(!$a%3)?$b='fizz':'';
if(!$a%5)$b.='buzz';
echo $b?$b:$a;}
Easy.. PHP as such:
$i=1;while($i<=100){if(!($i%15)){$output='fizzbuzz';}elseif(!($i%5)){$output='buzz';}elseif(!($i%3)){$output='fizz';}else{$output=$i;}print($output);echo "\n";$i++;}
Or does it need to be more readable?
$i = 1;
while ($i <= 100) {
if (!($i % 15)) {
$output = 'fizzbuzz';
} elseif (!($i % 5)) {
$output = 'buzz';
} elseif (!($i % 3)) {
$output = 'fizz';
} else {
$output = $i;
}
print ($output);
echo "\n";
$i++;
}
C# (114 characters, without spaces):
Enumerable.Range(1, 100).Select(a => a%15==0 ? "FizzBuzz" : a%3==0 ? "Fizz" : a%5==0? "Buzz" : a.ToString()).Run(Console.Write);
Mine one in C# using For Loop also we can use foreach one also
var i = 1;
for (i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Response.Write("FizzBuzz \n");
}
else if (i % 3 == 0)
{
Response.Write("Fizz \n");
}
else if (i % 5 == 0)
{
Response.Write("Buzz \n");
}
else
{
Response.Write(i);
}
}
foreach(range(1, 100) as $n) {
if(is_int($n/3) && is_int($n/5)) { print 'FizzBuzz<br/>'; }
elseif(is_int($n/3)) { print 'Fizz<br/>'; }
elseif(is_int($n/5)) { print 'Buzz<br/>'; }
else { print $n.'<br/>'; }
}
My PHP version, using is_int() to tell if it evenly divides and using range() to make an array of numbers from 1 to 100 pretty quickly.
Edit: Condensed.
<?php foreach(range(1, 100) as $n) { if(is_int($n/3) && is_int($n/5)) { print 'FizzBuzz'; } elseif(is_int($n/3)) { print 'Fizz'; } elseif(is_int($n/5)) { print 'Buzz'; } else { print $n.''; } } ?>
Nobody wrote a dc entry!!!
Here it is... (65 chars for golf)
[[Fizz]P]sF[[Buzz]P]sB[dn]sN100[dd3%d0=Fr5%d0=B*0!=NAP1-d0<L]dsLx
how about some ANSI C..
int state;
for(int i = 1; i <=100;i++)
{
state = ((i%3) == 0) + (((i%5) == 0) <<1);
if((state & 1) == 1)printf("Fizz");
if((state & 2) == 2)printf("Bang");
if(state == 0) printf("%i",i);
}
or even shorter:
char *c[] = {"%i \0","Fizz \0", "Buzz \0", "FizzBuzz \0"};
for(int i = 0; i < 100; printf(c[((i%3)==0)+(((i%5)==0)<<1)], i))i++;
In Perl:
use strict;
use warnings;
for my $num (1 .. 100)
{
my $str = '';
$str .= "Fizz" unless $num % 3;
$str .= "Buzz" unless $num % 5;
print $str || $num , "\n";
}
This would be a good interview for a Perl job because it can reveal
how perlish or Cish the programmer thinks. e.g. I would not be
impressed by an intermediate-level programmer writing a C-style solution
(for ($i = 1; $i <= 100; $i++)
, if-blocks with indentation (i.e. if (blah) { stuff }
rather than stuff if blah
), etc).
In PHP using the under appreciated ternary operator ?: You either love it or hate it.
<?php
foreach (range(1,100) as $i)
echo $i % 3 == 0 ? ( $i % 5 == 0 ? "FizzBuzz\n" : "Fizz\n" ) : ( $i % 5 == 0 ? "Buzz\n" : $i."\n" );
?>
Ruby using Enumerable#collect.
(1..100).collect { |x| x%15==0 ? "fizzbuzz" : x%3==0 ? "fizz" : x%5==0 ? "buzz" : x }
a basic action script version
fizzBuzz(100);
function fizzBuzz(i:int) {
var a:int=0;
while (a<i) {
a++;
if ( a%3 == 0 && a%5 == 0 ) {
trace("fizzBuzz");
} else if ( a%3 == 0 ) {
trace("fizz");
} else if ( a%5 == 0 ) {
trace("buzz ");
} else {
trace(a);
}
}
}
Another C version (139 chars)
#include <stdio.h>
int main(){int i=0;while(++i<101){((i%3==0?printf("Fizz"):0)|(i%5==0?printf("Buzz"):0))==0?printf("%d", i):0;puts("");}}
Readable*:
#include <stdio.h>
int main()
{
int i = 0;
while(++i < 101)
{
((i % 3 == 0 ? printf("Fizz") : 0) | (i % 5 == 0 ? printf("Buzz") : 0)) == 0 ? printf("%d", i) : 0; puts("");
}
}
Lesson learned is this: Never search for "What is the definition of enterprise software?" on SO as it inevitably leads you to Enterprise FizzBuzz.
Unfortunately if you are reading this warning, it's already too late.
My little javascript solution:
(function(i){if(i){arguments.callee(--i); console.log(i%15 ? (i%3 ? (i%5 ? i : 'Buzz') : 'Fizz') : 'FizzBuzz')}})(101);
Notice that it requires the firebug console or something else. I feel the code that goes as console.log parameter must be improved!
This is rather late to the party, but here is my python version in 100 characters:
print '\n'.join((("Fizz" if (x%3==0)else"")+("Buzz"if(x%5==0)else"")or str(x)for x in xrange(100)))
Written in jass, 1738 characters. Jass is the language which is used in order to create Warcraft 3 modules.
function Trig_fizzbuzz_Copy_Func001Func001Func002Func002C takes nothing returns boolean
if ( not ( ModuloInteger(GetForLoopIndexA(), 3) == 0 ) ) then
return false
endif
return true
endfunction
function Trig_fizzbuzz_Copy_Func001Func001Func002C takes nothing returns boolean
if ( not ( ModuloInteger(GetForLoopIndexA(), 5) == 0 ) ) then
return false
endif
return true
endfunction
function Trig_fizzbuzz_Copy_Func001Func001C takes nothing returns boolean
if ( not ( ModuloInteger(GetForLoopIndexA(), 15) == 0 ) ) then
return false
endif
return true
endfunction
function Trig_fizzbuzz_Copy_Actions takes nothing returns nothing
set bj_forLoopAIndex = 1
set bj_forLoopAIndexEnd = 100
loop
exitwhen bj_forLoopAIndex > bj_forLoopAIndexEnd
if ( Trig_fizzbuzz_Copy_Func001Func001C() ) then
call DisplayTextToForce( GetPlayersAll(), "TRIGSTR_017" )
else
if ( Trig_fizzbuzz_Copy_Func001Func001Func002C() ) then
call DisplayTextToForce( GetPlayersAll(), "TRIGSTR_016" )
else
if ( Trig_fizzbuzz_Copy_Func001Func001Func002Func002C() ) then
call DisplayTextToForce( GetPlayersAll(), "TRIGSTR_015" )
else
call DisplayTextToForce( GetPlayersAll(), I2S(GetForLoopIndexA()) )
endif
endif
endif
call TriggerSleepAction( 0.10 )
set bj_forLoopAIndex = bj_forLoopAIndex + 1
endloop
call CustomDefeatBJ( Player(0), "TRIGSTR_018" )
endfunction
//===========================================================================
function InitTrig_fizzbuzz_raw takes nothing returns nothing
set gg_trg_fizzbuzz_raw = CreateTrigger( )
call TriggerRegisterTimerEventSingle( gg_trg_fizzbuzz_raw, 1.00 )
call TriggerAddAction( gg_trg_fizzbuzz_raw, function Trig_fizzbuzz_Copy_Actions )
endfunction
A little bit late =P but here is my answer
EDIT: made it shorter - 99 chars
C#
for(int i=1;i<=100;i++){Console.Write(i%3==0?i%5==0?"FizzBuzz":"Fizz":i%5==0?"Buzz":i.ToString());}
Another Java solution, without cheating but with a couple of shorcuts (130 chars):
class L{public static void main(String[]a){for(int i=0;i++<100;)System.out.println((i%3>0?"":"fizz")+(i%5>0?i%3>0?i:"":"buzz"));}}
By using the same cheat as Isaac (runs but you get exception), you can get it down to 102 chars:
class J{static{for(int i=0;i++<100;)System.out.println((i%3>0?"":"fizz")+(i%5>0?i%3>0?i:"":"buzz"));}}
By really cheating, 68 chars:
class C{public static void main(String[]a){System.out.print(a[0]);}}
and passing "1 2 fizz 4 buzz ..." on the command line ;-)
Perl:
#!/usr/bin/env perl
use strict;
use warnings;
foreach my $i (1 .. 100)
{
print
!($i % 15)
? 'FizzBuzz'
: !($i % 5)
? 'Buzz'
: !($i % 3)
? 'Fizz'
: $i;
print "\n";
}
As a one-liner:
perl -e 'print $_%15?$_%5?$_%3?$_:"Fizz":"Buzz":"FizzBuzz","\n"for(1..100)'
TI-BASIC:
:For(X,1,100)
:If not(fPart(X/3))
:Disp "FIZZ"
:If not(fPart(X/5))
:Disp "BUZZ"
:If fPart(X/5)≠0 and fPart(x/3)≠0
:Disp X
:End
MSIL, 28 instructions, no locals
I noticed an earlier entry for MSIL by Jon Galloway [1], which I thought I could throw some time at. This is the result. (I'm not sure if I should be editing his answer since the original question asks about personal solutions, and not a optimized language contest. Writing stuff in someone else's name just feels wrong.)
.assembly extern mscorlib {}
.assembly fizzbuzz {.ver 1:0:1:0}
.module fizzbuzz.exe
.method static void main() cil managed {
.entrypoint
.maxstack 3
ldc.i4.0
_beginLoop:
ldc.i4.1
add
dup
ldc.i4.s 101 // loop end
ceq
brtrue.s _end
dup
ldc.i4.3
rem
brtrue.s _notThree
ldstr "Fizz"
call void [mscorlib]System.Console::Write(string)
_notThree:
dup
ldc.i4.5
rem
brtrue _notFive
ldstr "Buzz"
call void [mscorlib]System.Console::Write(string)
_notFive:
call int32 [mscorlib]System.Console::get_CursorLeft()
brtrue.s _threeOrFive
dup
call void [mscorlib]System.Console::WriteLine(int32)
br.s _beginLoop
_threeOrFive:
call void [mscorlib]System.Console::WriteLine()
br.s _beginLoop
_end:
pop
ret
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/4059#4059Based on this [1] and this [2] I came up with the following idea:
class FBFunct():
def __init__(self, start = 1, max = 100):
self.conditions = []
self.start = start
self.max = max
def __call__(self):
for i in range(self.start, self.max + 1):
print(''.join(next(cond) for cond in self.conditions) or i)
def addCondition(self, generator):
self.conditions.append(generator)
The usage is simple:
def div3():
while True:
yield ""
yield ""
yield "Fizz"
def div5():
while True:
yield ""
yield ""
yield ""
yield ""
yield "Buzz"
f = FBFunct()
f.addCondition(div3())
f.addCondition(div5())
f()
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/21251#21251The bad way ;)
VB.NET .NET 4 - VS 2010
Sub Main()
Dim fizz() As Char =
{"F"c, "i"c, "z"c} ' save 1 char by storing z only once
Dim buzz() As Char =
{"B"c, "u"c} ' cool! save another 2 chars by storing z only once
Dim lettersPrinted As Boolean
For i As Double = 1.0 To 1.0 * 100.0 Step 1 / 2 ' going slowly makes things more secure
lettersPrinted = False
' only integer numbers, please
If Math.Floor(i) <> i Then Continue For
' is i divisible by 3?
If Math.Floor(i / 3) = i / 3 Then
Dim fizzIndex As Integer = 0
Console.Write(fizz(fizzIndex))
fizzIndex = fizzIndex + 1
Console.Write(fizz(fizzIndex))
fizzIndex = fizzIndex + 1
Console.Write(fizz(fizzIndex))
' optimization: do not increment index!
Console.Write(fizz(fizzIndex))
lettersPrinted = True
End If
' is i divisible by 5?
If Math.Floor(i / 5) = i / 5 Then
Dim buzzIndex As Integer = 0
Dim fizzIndex As Integer = fizz.Length - 1 ' point to last char, which is the letter z
Console.Write(buzz(buzzIndex))
buzzIndex = buzzIndex + 1
Console.Write(buzz(buzzIndex))
' optimization: write the "z"s in a loop
For j As Integer = 0 To 1
Console.Write(fizz(fizzIndex))
Next
' optimization: only set letterPrinted to true if it's false
If lettersPrinted = False Then
lettersPrinted = True
Else
' don't change lettersPrinted
lettersPrinted = lettersPrinted
End If
End If
If lettersPrinted Then
' nothing to do
Else
Console.Write(i.ToString)
End If
' new line
Console.WriteLine()
Next i
End Sub
In Haskell, as clear as I could get it:
import Data.List
fizzbuzz :: Integer -> String
fizzbuzz x
| x `mod` 15 == 0 = "fizzbuzz"
| x `mod` 5 == 0 = "buzz"
| x `mod` 3 == 0 = "fizz"
| otherwise = show x
fizzbuzz100 = intercalate " " . map fizzbuzz $ [1..100]
That was my first Haskell program. :)
In C, done as a tangly mess, as a rant against tangly messes:
#include <stdio.h>
main(){
int i;
for (i=1;i<90;i+=15) {
printf("%d %d fizz %d buzz fizz %d %d fizz buzz %d fizz %d %d fizzbuzz ",
i, i+1, i+3, i+6, i+7, i+10, i+12, i+13);
}
printf("%d %d fizz %d buzz fizz %d %d fizz buzz\n", i, i+1, i+3, i+6, i+7);
}
In fortran, just for fun:
c FORTRAN fizzbuzz
program main
implicit none
integer i
logical i3
logical i5
do i = 1, 100
i3 = .false.
i5 = .false.
if ( i / 5 * 5 .eq. i ) then
i3 = .true.
end if
if ( i / 3 * 3 .eq. i ) then
i5 = .true.
end if
if ( i5 .and. i3 ) then
write ( *, '(a)' ) 'fizzbuzz'
end if
if ( i5 ) then
write ( *, '(a)' ) 'buzz'
end if
if ( i3 ) then
write ( *, '(a)' ) 'fizz'
end if
if ( .not. i3 .and. .not. i5 ) then
write ( *, '(i2)') i
end if
end do
stop
end
In fortran of an older style:
C FIZZBUZZ
PROGRAM MAIN
101 FORMAT (A)
102 FORMAT (I2)
INTEGER I
INTEGER I3
INTEGER I5
INTEGER J
I = 0
401 J = I
I = J + 1
501 IF (I-100) 502, 502, 701
502 I3 = 0
J = I / 3 * 3
IF (I - J) 701, 511, 512
511 I3 = 1
512 I5 = 0
J = I / 5 * 5
IF (I - J) 701, 521, 522
521 I5 = 1
522 IF (I3 + I5 - 1) 531, 541, 551
531 WRITE (*, 102), I
GOTO 401
541 IF (I3) 701, 542, 545
542 WRITE (*, 101), 'FIZZ'
GOTO 401
545 WRITE (*, 101), 'BUZZ'
GOTO 401
551 WRITE (*, 101), 'FIZZBUZZ'
GOTO 401
701 STOP
END
Good ol' C, nothing beats that! Here's a version with no mods or divides...
#include <stdio.h>
int
main()
{
int three_count = 0;
int five_count = 0;
int val;
for (val = 1; val <= 100; val++)
{
three_count++;
five_count++;
if (three_count != 3 && five_count != 5)
{
printf("%d", val);
}
else
{
if (three_count == 3)
{
printf("Fizz");
three_count = 0;
}
if (five_count == 5)
{
printf("Buzz");
five_count = 0;
}
}
printf("\n");
}
return 0;
}
Here's another solution...
/*
* Better than my previous attempt? You decide.
*/
#include <stdio.h>
int
main()
{
int fifteen_count = 0;
int val;
for (val = 1; val <= 100; val++)
{
fifteen_count++;
switch (fifteen_count)
{
case 3:
case 6:
case 9:
case 12:
printf("Fizz\n");
break;
case 5:
case 10:
printf("Buzz\n");
break;
case 15:
printf("FizzBuzz\n");
fifteen_count = 0;
break;
default:
printf("%d\n", val);
break;
}
}
return 0;
}
Now that I have attempted this, I see there is a balance between redundancy and simplicity, where there is no pretty solution to. Bummer
Here is my best in PHP:
for($i=1; $i<=100; $i++){
if ($i%3) echo 'Fizz';
if ($i%5) echo 'Buzz';
if (!$i%3 && !$i%5) echo $i; //I know I could optimize with %15, but that would be less clear
}
A Ruby solution that uses neither division nor modulus:
puts (1..100).map{|i|
o=""
o<<"Fizz" if ('o' * i) =~ /^$|^(...)\1*$/
o<<"Buzz" if ('o' * i) =~ /^$|^(.....)\1*$/
o=i.to_s if o.empty?
o
}
I know that there was already answer with erlang implementation [1], but it was only sequential usage of erlang. But having erlang let's actually spawn some processes! And as a bonus another version of sequential approach using map instead of recursion.
-module(fizzbuzz).
-compile(export_all).
fizzbuzz(N) when N rem 15 == 0 ->
"fizzbuzz";
fizzbuzz(N) when N rem 3 == 0 ->
"fizz";
fizzbuzz(N) when N rem 5 == 0 ->
"buzz";
fizzbuzz(N) ->
N.
pmap(F, L) ->
Parent = self(),
[receive {Pid, Result} -> Result end
|| Pid <-
[spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]].
% make decisions in parallel
par(N) when N >= 1 ->
lists:foldl(
fun(X,_) -> io:format("~p~n",[X]) end, [],
pmap(fun fizzbuzz/1, lists:seq(1,N)));
par(_) -> badarg.
% make decisions sequentially
seq(N) when N >= 1 ->
lists:foldl(
fun(X,_) -> io:format("~p~n",[X]) end, [],
lists:map(fun fizzbuzz/1, lists:seq(1,N)));
seq(_) -> badarg.
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/461315#461315Quickie C# (141 139 chars):
public static void O(int i){Console.WriteLine((i%3==0&&i%5==0)?"FizzBuzz":(i%3==0)?"Fizz":(i%5==0)?"Buzz":i.ToString());if(i<100){O(i+1);}}
((0 i.~15 3 5|]){::'FizzBuzz';'Fizz';'Buzz';":)"0>:i.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
Oracle SQL (precondition table with 1 - 100)
select decode(mod(id,3),0, decode(mod(id,5),0,'fizzbuzz','fizz'), decode(mod(id,5),0,'buzz,id)) from fizzbuzz
PHP with switch.
I always thought that this switch evaluation rocks, but probably it's just me hating the if's and loving the switch
<?php
foreach(range(0,99) as $number) {
switch(0) {
case $number % 15:
echo "fizzbuzz";
break;
case $number % 5:
echo "fizz";
break;
case $number % 3:
echo "buzz";
break;
default:
echo $number;
break;
}
echo "\n";
}
?>
Ok, here's a recursive solution based on my JavaScript solution [1]. Just another variant...
var output = fizzBuzz(1, 100);
function fizzBuzz(i, max){
var fizz = (i % 3 == 0);
var buzz = (i % 5 == 0);
var tmpOutput = "";
if(!fizz && !buzz){
tmpOutput = i;
}else{
if(fizz){
tmpOutput = "Fizz";
}
if(buzz){
tmpOutput += "Buzz";
}
}
tmpOutput += "<br />";
if(i < max){
i++;
tmpOutput += fizzBuzz(i, max);
}
return tmpOutput;
}
document.write(output);
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem#577In REBOL:
ifmod: func [a n] [either (mod a n) = 0 [n] [0]]
for a 1 100 1 [
print switch (ifmod a 5) + (ifmod a 3) [
8 ["FizzBuzz"]
5 ["Buzz"]
3 ["Fizz"]
0 [a]
]
]
In UniBasic:
FOR XX = 1 TO 100
MULT.OF.THREE = NOT(MOD(XX,3))
MULT.OF.FIVE = NOT(MOD(XX,5))
BEGIN CASE
CASE MULT.OF.THREE AND MULT.OF.FIVE
PRINT "FizzBuzz"
CASE MULT.OF.FIVE
PRINT "Buzz"
CASE MULT.OF.THREE
PRINT "Fizz"
CASE 1
PRINT XX
END CASE
NEXT XX
Here is an XSLT version.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="text" version="1.0" encoding="UTF-8" indent="no" />
<xsl:template match="/">
<xsl:for-each select="1 to 100">
<xsl:choose>
<xsl:when test="position() mod 3=0">
fizz
<xsl:if test="position() mod 5=0">
buzz
</xsl:if>
</xsl:when>
<xsl:when test="position() mod 5=0">
buzz
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="position()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Or much smaller in a function:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of select="for $n in (1 to 100) return if ($n mod 3 = 0) then if($n mod 5=0) then 'fizzbuzz ' else 'fizz' else if($n mod 5=0) then 'buzz' else $n"/>
</xsl:template>
</xsl:stylesheet>
The shortest I could do with php (70 characters):
<?php while($i++<100)echo($i%15?$i%3?$i%5?$i:Buzz:Fizz:FizzBuzz)."\n";
Java, 130 characters:
public class A{static{for(int i=1;i<100;i++) {boolean b=i%3==0,c=i%5==0;System.out.println(b||c?(b?"Fizz":"")+(c?"Buzz":""):i);}}}
Now, this is kinda cheating, because when you run it at the end it will say:
Exception in thread "main" java.lang.NoSuchMethodError: main
But it still works....
Yet Another T-SQL Variation (hadn't seen this one yet):
declare @var char(8)
declare @counter int
set @var = 0
set @counter = 0
while @counter < 100
begin
set @counter = @counter +1
set @var = @counter
while @counter % 3 = 0 or @counter % 5 = 0
begin
if @counter % 3 = 0
set @var = 'Fizz'
if @counter % 5 = 0
set @var = 'Buzz'
if @counter % 15 = 0
set @var = 'FizzBuzz'
break
end
print @var
set @var = 0
end
ok, my 0.02$
for(int i=0;i<100;i++) printf(((!i%3)+(!i%5))?((!i%3)?"Fizz":"")+((!i%5)?"Buzz":"":i));
It's not pretty and it needs documentation, but it's fun!
perl -e'foreach $x ( 1 .. 100) { if( $x % 3 == 0 ) { print "Fizz"; } if( $x % 5 == 0 ) { print "Buzz"; }unless ( $x % 3 == 0 || $x % 5 == 0 ) { print "$x" } print "\n"; }'
Works, but could probably stand more obfuscation.
Using the new Proc#=== in Ruby 1.9:
def divisible_by(factor)
lambda {|product| product.modulo( factor ).zero? }
end
1.upto 100 do |number|
puts case number
when divisible_by 15: "FizzBuzz"
when divisible_by 3: "Fizz"
when divisible_by 5: "Buzz"
else: number
end
end
Use fizzbuzz-maker. You run it and it writes out a file called fizzbuzz.exe, which when run, shows the output required of the original poster.
Because the source code is zero bytes, it wins.
D (Digital Mars):
#!/usr/bin/dmd -run
/**
* to compile & run:
* $ dmd -run fizzbuzz.d
* to optimize:
* $ dmd -O -inline -release fizzbuzz.d
*/
import std.stdio: writeln;
import std.string: toString;
void main() {
for (int i = 1; i <= 100; i++)
writeln(i % 15 == 0 ? "FizzBuzz" :
i % 3 == 0 ? "Fizz" :
i % 5 == 0 ? "Buzz" : toString(i));
}
I'm not very good at golf. Here's 74
characters in Python:
for n in range(1,101):print(""if n%3 else"Fizz")+(""if n%5 else"Buzz")or n
There are many ways to write this in Perl 6. This isn't the smallest, but it does show an interesting feature of the language. It can now run in Rakudo Perl 6 right now:
multi sub p(Int $x where {!($^n%3 || $^n%5)}) { "FizzBuzz" };
multi sub p(Int $x where {!($^n%3) && $^n%5}) { "Fizz" };
multi sub p(Int $x where {!($^n%5) && $^n%3}) { "Buzz" };
multi sub p(Int $x) { return $x; };
for (1..100) -> $x { say p($x) }
Yet another C version (77 chars). People at anarchy golf [1] have managed to bring it down to 73, but as a newbie golfer I can't find any more corners to cut. Ideas?
main(i){while(i<101)printf(i%3?i%5?"%d":"":"Fizz",i)|puts(i++%5?"":"Buzz");}
[1] http://www.shinh.org/l.rb?cOmg. It seems a challenge :P Readable version, in python :-)
for n in xrange(1,101):
s = ''
if n%3 == 0: s += 'Fizz'
if n%5 == 0: s += 'Buzz'
if s == '': s = n
print s
Here's one I did a while ago in Haskell (generalized & should run very quick -- no arithmetic is performed after the initial setup):
gizzabuzz pairs combiner = zipWith ($) (cycle funcs) [1..]
where
funcs = map (\n -> display $ mapMaybe (filterOut n) sortedPairs) [1..foldr1 lcm $ map fst $ sortedPairs]
display [] = show
display xs = foldr1 combiner . sequence (map const xs)
sortedPairs = sortBy (compare `on` fst) pairs
filterOut n (x,y)
| n `mod` x == 0 = Just y
| otherwise = Nothing
fizzbuzz = gizzabuzz [(3,"Fizz"),(5,"Buzz")] (++)
Glad to post the first response in C ;)
int main(int argc, _TCHAR* argv[])
{
for(int i = 0; i < 100 ; i++)
{
if(i%3)
{
if(i%5)
{
printf("FizzBuzz");
}
else
{
printf("Fizz");
}
}
else if(i%5)
{
printf("Buzz");