# FizzBuzz Solution Dumping Ground

#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``````

#204

No C/SIDE?

OnRun()
Message(FizzBuzz);

FizzBuzz() Out : Text[1024]
FOR i := 1 to 100 DO BEGIN
IF i MOD 3 = 0 THEN
out += ‘Fizz’;
IF i mod 5 = 0 THEN
out += ‘Buzz’;
If NOT (i mod 3 = 0) AND NOT (i mod 5 = 0) THEN
out += Format(i);
out += ‘’;
END;

#205

A modern & practical approach … (written in Go in this case, but any language will do)

``````package main
import (
"fmt"
)

func main () {
fmt.Println( fizzbuzz(1,100) )
}
``````

Its not cheating, and it does address the original intention of the FizzBuzz problem.

I think this is a valid solution, because (for better or for worse), the ability to collaborate with total strangers and existing solutions has become an important tool in the programmer’s arsenal,

Its also idiomatic Go (GoLang), to #include directly into a 3rd party github repo, support for which is built into the language from day 1. The compiler manages the fetching, building, regression testing of the 3rd party libs, as they change over time.

Given that the spec for FizzBuzz may well change over time … each time you compile this code, it may update itself automatically, and produce a different result ???

This has some wide philosophical implications when you dwell on that.

You can easily achieve the same thing in any toolchain by writing some extra lines in your Makefile or whatever. Go just sticks it right in your face and makes it obvious.

Is this what the customer actually asked for ? Nope !
Is this what the customer actually meant ? Probably !

Will asking the customer to clarify what they meant yield a correct answer ? Not very likely !

#206
``````/*
* FizzBuzz implementation in Rust (Imperitive version (Ich!))
*/
fn main () {
for i in range(0i, 100i) {
if (i % 5 == 0) && (i % 3 == 0) { println!("FizzBuzz") }
else { println!("{}", i) }

if i % 3 == 0 { println!("Fizz") }
else { println!("{}", i) }

if i % 5 == 0 { println!("Buzz") }
else { println!("{}", i) }
}
}
``````
``````/*
* Rust Fizzbuzz functional implementation
*/
fn fb (i: int) -> () {
let mod5 = i % 5 == 0;
let mod3 = i % 3 == 0;

match [mod5, mod3] {
[false, true] => println!("Fizz"),
[true, false] => println!("Buzz"),
[false, false] => println!("{}", i),
[true, true] => println!("FizzBuzz")
}
}

fn fizzbuzz (up_to: int) -> () {
fb(up_to);
if up_to > 0 { fizzbuzz(up_to - 1) }
}

fn main () {
fizzbuzz(100)
}
``````

#207

And in Racket (a dielect of scheme)

``````
#lang racket
(define (fizz-buzz [end 100] [n 1])
(letrec ([FB (lambda (n)
(cond
((< n end)
(displayln
(match (gcd n 15)
[15 "fizzbuzz"]
[3 "fizz"]
[5 "buzz"]
[_ n]))
(FB n)))
``````

#208

And also in my very own programming language that I wrote in ruby (called Bike):

``````def fb (i) {
if i % 15 is 0 { println i }
if i % 3 is 0 { println "Fizz" }
if i % 5 is 0 { println "Buzz" }
}

def fizzbuzz (max) {
fb max
if max > 0 {
fizzbuzz max - 1
}
}
fizzbuzz 100
``````

here is the language on github (It is still in Beta 4):