a companion discussion area for blog.codinghorror.com

# FizzBuzz Solution Dumping Ground

#182

#Short and Sweet ruby answer :

puts (1…100).map{|i| i%15 == 0 ? “Fizzbuzz” : i%3 == 0 ? “Fizz” : i%5 == 0 ? “buzz” : “#{i}” }

#183

Python version:

``````for number in range(1, 101):
result = ""
if not number % 3:
result = "Fizz"
if not number % 5:
result += "Buzz"
if not result:
result = number
print result
``````

#184

in javascript, fun with lazy ||

``````for (var n = 1; n <= 100; ++n) {
console.log ((function() {
var s, t1 = n % 3 == 0, t2 = n % 5 == 0, t3 = t1 && t2;
if ((s = "fizzbuzz", t3) || (s = "fizz", t1) || (s = "buzz", t2))
return [n, " is ", s].join("");
return n;
})());

}
``````

http://jsfiddle.net/dimitar/F52fn/5/

#185

Sure this is an old thread, but I wanted to put my two cents in. In Java:

``````	String out = "";

for(int x = 1; x <= 100; x++){
//reset the variable with each loop
out = "";
//if the number is divisible by 3, show Fizz
if(x % 3 == 0) out += "Fizz";
//if the number is divisible by 5, show Buzz
if(x % 5 == 0) out += "Buzz";
//If neither case above, then show the number
if(out == "") out = ""+x;
System.out.println(out);``````

#186

This is my solution:

#187

A Scala REPL version…

``````for ( i <- 1 to 100 ) {
var f = if ( i%3 == 0 ) { "Fizz" } else { "" }
var b = if ( i%5 == 0 ) { "Buzz" } else { "" }
var r = if ( (f+b).size == 0 ) { i } else { f+b }
println ( r )
}``````

#188
``````for (int i = 0; i<100; i++)
{
if(i%3==0)
Console.Write("Fizz");
if(i%5==0)
{
Console.WriteLine("Buzz");
continue;
}
Console.Writeline(i.toString());

}
``````

#189

// Making it look good in java took me 4 min because I’m dumb and I’m still in high school.

``````public class FizzBuzzMultiples extends ConsoleProgram {

public void run() {
for(double i = 1; i<101; i++) {
int q = 0;
double j = i/5;

if(j%2 == 0) {
double ok = j/3;
if(ok%2 == 0) {
println(i+ "- FizzBuzz");
q = 1;
}
}
if(q == 0) {
if(i % 3 == 0) {
println(i+ "- Fizz");
}else if(i % 5 == 0) {
println(i+ "- Buzz");
} else {
println(i);
}
}

q = 0;
}
}
}``````

#190
``````<?php
for (\$i=1; \$i <= 100 ; \$i++) {
if(\$i % 3 === 0 && \$i % 5 !== 0){
echo 'Fizz<br>';
} else if(\$i % 5 === 0 && \$i % 3 !== 0){
echo 'Buzz<br>';
} else if(\$i % 5 === 0 && \$i % 3 === 0){
echo 'FizzBuzz<br>';
} else {
echo \$i.'<br>';
}
}
?>``````

#191

Ruby 1liner!

``````puts "#{"fizz" if inp % 3 == 0}#{buzz if inp % 5 == 0}"
``````

#192
``````> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > < < + > + > + + + > > > + + + + + >
> > + > + + + + + + + + + + > + + + + + + + + + + > + + +
+ + + + + + + > + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + > +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + > + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + > > > + + + + + < < < > > > > > > > > >
> > > > > > > > + + + + + + + [ < < < < < + + + + + + + +
+ + > > > > > - ] < < < < < - - - > > > > > + + + + + + +
+ + + + + [ < < < < + + + + + + + + + + > > > > - ] < < <
< - - - - - - > > > > + + + + + + + + + + [ < < < + + + +
+ + + + + + > > > - ] < < < - - - > > > + + + + + + + + +
+ [ < < + + + + + + + + + + > > - ] < < - > > + + + + + +
+ + + + + [ < + + + + + + + + + + > - ] < - - - > > + + +
+ + + + + + + + [ < + + + + + + + + + + > - ] < - - > > +
+ + + + + + + + + [ < + + + + + + + + + + > - ] < + > > +
+ + + + + + + [ < + + + + + + + + + + > - ] < > > + + + +
+ + + + + + + [ < + + + + + + + + + + > - ] < + > > + + +
+ + + + + + + + [ < + + + + + + + + + + > - ] < + + > < <
< < < < < < < < < < < < < < < < < < < < < < < < < < [ > >
> < < [ > > < [ > < < < < < < < < < > [ - ] + > [ - ] < <
[ > > > > > > > > > < < < < < < > [ - ] > [ - ] < < [ > +
> + < < - ] > [ < + > - ] > [ > > > > > > > > > [ < < < <
< . > > > > > > > [ - ] > [ - ] < < [ > + > + < < - ] > [
< + > - ] + > [ < - > [ - ] ] < [ < < < < < . > > > > > <
+ > - ] < - > < < < < . < < < > > > > > [ - ] ] + < < < <
< < < < < [ - ] ] > > > > < < < < < < < < < > - < [ > > +
< < - ] ] > > [ < < + > > - ] < [ > > > > > > > > . > > >
> > > > > > > > > > > > . > . > . > . > . > . > . < < < <
< < < < < < < < < < < < < < < < < < < < < < < > [ - ] > [
- ] < < [ > + > + < < - ] > [ < + > - ] + > [ < - > [ - ]
] < [ > > > > > > > > > > > > > > > > > > > > > > > > > >
> . > . > . < < < < < < < < < < < < < < < < < < < < < < <
< < < < < < < < < < < < [ - ] > > > > > > > > > > > < < <
< < - ] > > > > > < < < < < < < < < + + + < + + + + + + +
+ + + [ - ] + > > > > > > > > > > < < < < < < < < - ] > >
> > > > > > < < < < < < > [ - ] + > [ - ] < < [ > - < [ >
> + < < - ] ] > > [ < < + > > - ] < [ < + + + + + > > > >
> > < < < < < < < < < < [ < [ > > > > > > > > > > > . > >
> > > > > > > > > > > > > > > > > > > > . > . > . < < < <
< < < < < < < < < < < < < < < < < < < < < < < < < < < < <
< < - ] + > - ] + > > > > > > > > > > < < < < < - ] > > >
> > > > > + < < < < < < < < < < < < - > > > > > > > > > <
< < < < < - > > > > > > < - > > > > > - < < < < < ] + + +
+ + + + + + + > > > > - - - - - - - - - - < + < < < < - ]
+ + + + + + + + + + > > > > - - - - - - - - - - < + < < <
< - ] > > > . > > > > > > > > > > > > > > > > > > > > > >
. > . > . < < < < < < < < < < < < < < < < < < < < < < < <
``````

#193

Readable perl version ( intentionally always print the number in this case.):

``````#!/usr/bin/env perl

use strict;
use warnings;

foreach my \$number ( 1 .. 100 ) {
my \$string = "\$number ";
if ((\$number % 3) == 0) {
\$string .= 'fizz';
}
if ((\$number % 5) == 0) {
\$string .= 'buzz';
}
print "\$string\n";
}
``````

and here the version as specified, only printing fizz[buzz] or a number:

``````#!/usr/bin/env perl

use strict;
use warnings;

foreach my \$number ( 1 .. 100 ) {
my \$string;
if ((\$number % 3) == 0) {
\$string .= 'fizz';
}
if ((\$number % 5) == 0) {
\$string .= 'buzz';
}
\$string ||= \$number;

print "\$string\n";
}``````

#194
``````for(\$counter = 1; \$counter <= 100; \$counter++) {
echo (\$counter % 5 == 0 ? (\$counter % 3 == 0 ? "FizzBuzz" : "Buzz") : (\$counter % 3 == 0 ? "Fizz" : \$counter))."\n";
}
``````

Doesn’t win points for readability, but hey, that line count…

#195

Missing the numbers.

#198

Being of an evil mind tonight, I created the following debacle for your… entertainment:

``````#!r6rs

(import
(rnrs base (6))
(rnrs lists (6))
(rnrs r5rs (6))
(rnrs io simple (6)))

(define (factor? x y)
(= 0 (modulo x y)))

(define (series)
(letrec ((next
(lambda (n)
(cons n (delay (next (+ n 1)))))))
(next 1)))

(define (show x)
(display x)
#t)

(define-syntax exclusive-or
(syntax-rules ()
((_ x y)
(let ((a x)
(b y))
(and (or a b) (not (and a b)))))))

(define (fizzbuzz)
(let I-am-off ((to-infinity-and-beyond (series)))
(let ((n (car to-infinity-and-beyond)))
(if (exclusive-or
(and (factor? n 3) (show 'fizz))
(and (factor? n 5) (show 'buzz)))
'()
(if (not (factor? n 15))
(display n)))
(display #\space)
(I-am-off (force (cdr to-infinity-and-beyond))))))

(fizzbuzz)``````

#199

Someone mentioned writing this as code that generates FizzBuzz in your choice of languages? (with a little WTF thrown in, of course)

Put this in the void Main of a C# console app and watch the magic happen.

``````        CompilerInfo[] langInfo = CodeDomProvider.GetAllCompilerInfo();
for (int i = 0; i < langInfo.Length; i++)
if (langInfo[i].IsCodeDomProviderTypeValid)
Console.WriteLine("{0} - {1}", i + 1, langInfo[i].CodeDomProviderType.Name);
Console.WriteLine();
ConsoleKeyInfo nullKey = new ConsoleKeyInfo('.', ConsoleKey.Decimal, false, false, false);
ConsoleKeyInfo langSelKey = nullKey;
while (langSelKey == nullKey)
{
int iKeyCharVal;
if (int.TryParse(tempKeyInfo.KeyChar.ToString(), out iKeyCharVal) && iKeyCharVal > 0 && iKeyCharVal <= langInfo.Length)
langSelKey = tempKeyInfo;
else
Console.WriteLine("?");
}
int iKeyCharValAgain = -1;
if (langSelKey.KeyChar != null)
int.TryParse(langSelKey.KeyChar.ToString(), out iKeyCharValAgain);

bool compile = false;
Console.Write('\n');
Console.Write('\n');
ConsoleKeyInfo nullKey2 = new ConsoleKeyInfo('0', ConsoleKey.NumPad0, false, false, false);
ConsoleKeyInfo chooseCompileKey = nullKey2;
while (chooseCompileKey == nullKey2)
{
Console.Write('\n');
Console.Write("Compile output? ");
if (tempKeyInfo2.Key == ConsoleKey.Y || tempKeyInfo2.Key == ConsoleKey.N)
chooseCompileKey = tempKeyInfo2;
else
Console.WriteLine("?");
}
if (chooseCompileKey.Key == ConsoleKey.Y)
compile = true;
else
compile = false;

int countMax = 0;
Console.Write('\n');
bool hasMaxValue = false;
while (hasMaxValue == false)
{
Console.Write('\n');
Console.Write("\nCount how high? ");
if (!string.IsNullOrEmpty(strMaxCnt) && int.TryParse(strMaxCnt, out countMax))
hasMaxValue = true;
else
Console.WriteLine("?");
}

// Now the fun part starts.
CodeNamespace ns = new CodeNamespace("com.wtf.fizzbuzz");

CodeTypeDeclaration fzbzCls = new CodeTypeDeclaration("FizzBuzzOutputter");
fzbzCls.TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class;
fzbzCls.IsClass = true;

CodeMemberField maxField = new CodeMemberField(
new CodeTypeReference("System.Int32"), "_MaxCount");
maxField.Attributes = MemberAttributes.Public;

CodeConstructor cstr = new CodeConstructor();
cstr.Attributes = MemberAttributes.Public;
new CodeParameterDeclarationExpression(
new CodeTypeReference("System.Int32"), "max"));
new CodeFieldReferenceExpression(
new CodeThisReferenceExpression(),
"_MaxCount"
), new CodeArgumentReferenceExpression("max")));

CodeMemberMethod doMeth = new CodeMemberMethod();
doMeth.Name = "doMeth";
doMeth.Attributes = MemberAttributes.Public;
doMeth.ReturnType = new CodeTypeReference("System.String");
new CodeParameterDeclarationExpression(
new CodeTypeReference("System.Int32"), "countMax")
);

CodeIterationStatement forLooop = new CodeIterationStatement(
new CodeVariableDeclarationStatement(
new CodeTypeReference(
new CodeTypeParameter("System.Int32")
), "i", new CodePrimitiveExpression(0)
), new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("i"),
CodeBinaryOperatorType.LessThan,
new CodeArgumentReferenceExpression("countMax")
), new CodeAssignStatement(
new CodeVariableReferenceExpression("i"),
new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("i"),
new CodePrimitiveExpression(1)
)
));

CodeVariableDeclarationStatement varX = new CodeVariableDeclarationStatement(
"System.Int32", "x", new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("i"),
new CodePrimitiveExpression(1)
));

CodeConditionStatement ifFizzBuzz = new CodeConditionStatement();
ifFizzBuzz.Condition = new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("x"),
CodeBinaryOperatorType.Modulus,
new CodePrimitiveExpression(5)
), CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(0)
), CodeBinaryOperatorType.BooleanAnd
, new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("x"),
CodeBinaryOperatorType.Modulus,
new CodePrimitiveExpression(3)
), CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(0)
));
new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
), "WriteLine", new CodePrimitiveExpression("FizzBuzz")
));
CodeConditionStatement elseIfFizz = new CodeConditionStatement(
new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("x"),
CodeBinaryOperatorType.Modulus,
new CodePrimitiveExpression(3)
), CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(0)
));
new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
), "WriteLine", new CodePrimitiveExpression("Fizz")
));
CodeConditionStatement elseIfBuzz = new CodeConditionStatement(
new CodeBinaryOperatorExpression(
new CodeBinaryOperatorExpression(
new CodeVariableReferenceExpression("x"),
CodeBinaryOperatorType.Modulus,
new CodePrimitiveExpression(5)
), CodeBinaryOperatorType.ValueEquality,
new CodePrimitiveExpression(0)
));
new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
), "WriteLine", new CodePrimitiveExpression("Buzz")
));
new CodeMethodInvokeExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
), "WriteLine", new CodeVariableReferenceExpression("x")
));

new CodeMethodReturnStatement(
new CodeMethodInvokeExpression(
new CodeArgumentReferenceExpression("countMax"),
"ToString"
)
));

CodeTypeDeclaration progMainCls = new CodeTypeDeclaration("Program");

CodeMethodInvokeExpression consWrite = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
), "WriteLine"
), new CodePrimitiveExpression("Press any key to fizz/buzz..."));
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
));

CodeEntryPointMethod voidMan = new CodeEntryPointMethod();
new CodeTypeReference(typeof(object[])), "args"));
new CodeVariableDeclarationStatement(
new CodeTypeReference("FizzBuzzOutputter"),
"inst",
new CodeObjectCreateExpression(
new CodeTypeReference("FizzBuzzOutputter"),
new CodePrimitiveExpression(countMax)
)
));
new CodeMethodInvokeExpression(
new CodeVariableReferenceExpression("inst"),
"doMeth",
new CodePrimitiveExpression(countMax)
));
new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(
new CodeTypeReferenceExpression(
new CodeTypeReference(typeof(Console))
), "WriteLine"
), new CodePrimitiveExpression("Press any key to exit...")));   // And by "any key", I mean <Enter> :)

CodeCompileUnit cdCmpUnt = new CodeCompileUnit();

// Finally ready to output the result.
CodeDomProvider provider = langInfo[iKeyCharValAgain - 1].CreateProvider();
CodeGeneratorOptions opts = new CodeGeneratorOptions();
opts.BlankLinesBetweenMembers = false;
opts.ElseOnClosing = true;

StringBuilder sbOutput = new StringBuilder();
using (System.IO.StringWriter sr = new System.IO.StringWriter(sbOutput))
provider.GenerateCodeFromCompileUnit(cdCmpUnt, sr, opts);

Console.WriteLine(sbOutput);

Console.Write('\n');
Console.Write('\n');
Console.Write("\nSpecify file name: ");
string outPath = System.IO.Path.Combine(Environment.CurrentDirectory, outFileNm);
if (compile)
{
CompilerParameters compParams = new CompilerParameters();
compParams.WarningLevel = 3;
compParams.CompilerOptions = "/optimize";
compParams.GenerateExecutable = true;
compParams.IncludeDebugInformation = false;
compParams.GenerateInMemory = false;
if (provider.Supports(GeneratorSupport.EntryPointMethod))
compParams.MainClass = "com.wtf.fizzbuzz.Program";
compParams.OutputAssembly = outPath + ".exe";
CompilerResults compResult = provider.CompileAssemblyFromDom(compParams, cdCmpUnt);
if (compResult.Errors.Count == 0)
Console.WriteLine("File created at: " + compResult.PathToAssembly);
else
{
Console.WriteLine("This following errors occured durring compilation:");
for (int i = 0; i < compResult.Errors.Count; i++)
Console.WriteLine("\t- {0}", compResult.Errors[i].ErrorText);
}
}
else
{
using (System.IO.FileStream fs = new System.IO.FileStream(outPath, System.IO.FileMode.Create, System.IO.FileAccess.Write))
using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs))
sr.Write(sbOutput.ToString());
}

Console.WriteLine();
Console.WriteLine("ALL DONE!  Press <Enter> to exit.");

#200

In php:

``````\$i;
for(\$i=0; \$i <=100; \$i++)
{
\$printint=true;
if(\$i % 5 == 0) {echo "buzz <br/>"; \$printint=false;}
if(\$i % 3 == 0) {echo "fizz <br/>"; \$printint=false;}
if(\$printint==true) echo \$i . "<br/>";
}``````

#201

One more PHP solution, just because this is using neither loops nor recursion.

``````print implode(' ', array_map(function(\$n) {
return ((\$n % 3 === 0 ? 'Fizz' : '').(\$n % 5 === 0 ? 'Buzz' : '')) ?: \$n;
}, range(1, 100)));
``````

#202

Short and simple solution in Java.

``````for(int i = 1; i <= 100; i++){
String fizz = i % 3 == 0 ? "Fizz" : "";
String buzz = i % 5 == 0 ? "Buzz" : "";
String print = (fizz+buzz).length() == 0 ? Integer.toString(i) : fizz+buzz;
System.out.println(print);
}
``````

edit. Figured out a shorter way just after I posted this.

``````for(int i = 1; i <= 100; i++){
String fzbz = (i % 3 == 0 ? "Fizz" : "")+(i % 5 == 0 ? "Buzz" : "");
System.out.println(fzbz = fzbz.length() == 0 ? Integer.toString(i) : fzbz);
}``````

#203

FizzBuzz looks like it was derived from the first problem in Project Euler. There are 484 problems in that set.

This is the Project Euler text for Problem One: “If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.”

Here is a quick hacked version for fizzbuzz.hs:

``````main = print \$ map fizzBuzz [1..100]
where
fizzBuzz n
| n `mod` 15==0   = "FizzBuzz"
| n `mod` 3==0    = "Fizz"
| n `mod` 5==0    = "Buzz"
| otherwise = show n
``````

This is a quick data driven solution of fizzbuzz.hs:

``````threes = cycle ["","","fizz"]
fives  = cycle ["","","", "", "buzz"]
fizzBuzz = zipWith (++) threes fives

compose (n,s)
| s=="" = show n
| otherwise = s

main = print . map compose \$zip [1..100] fizzBuzz``````