FizzBuzz Solution Dumping Ground

Ruby 1liner!

puts "#{"fizz" if inp % 3 == 0}#{buzz if inp % 5 == 0}"
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
> > > > > > > > > > > < < + > + > + + + > > > + + + + + >
> > + > + + + + + + + + + + > + + + + + + + + + + > + + +
+ + + + + + + > + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + > +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + > + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + > > > + + + + + < < < > > > > > > > > >
> > > > > > > > + + + + + + + [ < < < < < + + + + + + + +
+ + > > > > > - ] < < < < < - - - > > > > > + + + + + + +
+ + + + + [ < < < < + + + + + + + + + + > > > > - ] < < <
< - - - - - - > > > > + + + + + + + + + + [ < < < + + + +
+ + + + + + > > > - ] < < < - - - > > > + + + + + + + + +
+ [ < < + + + + + + + + + + > > - ] < < - > > + + + + + +
+ + + + + [ < + + + + + + + + + + > - ] < - - - > > + + +
+ + + + + + + + [ < + + + + + + + + + + > - ] < - - > > +
+ + + + + + + + + [ < + + + + + + + + + + > - ] < + > > +
+ + + + + + + [ < + + + + + + + + + + > - ] < > > + + + +
+ + + + + + + [ < + + + + + + + + + + > - ] < + > > + + +
+ + + + + + + + [ < + + + + + + + + + + > - ] < + + > < <
< < < < < < < < < < < < < < < < < < < < < < < < < < [ > >
> < < [ > > < [ > < < < < < < < < < > [ - ] + > [ - ] < <
[ > > > > > > > > > < < < < < < > [ - ] > [ - ] < < [ > +
> + < < - ] > [ < + > - ] > [ > > > > > > > > > [ < < < <
< . > > > > > > > [ - ] > [ - ] < < [ > + > + < < - ] > [
< + > - ] + > [ < - > [ - ] ] < [ < < < < < . > > > > > <
+ > - ] < - > < < < < . < < < > > > > > [ - ] ] + < < < <
< < < < < [ - ] ] > > > > < < < < < < < < < > - < [ > > +
< < - ] ] > > [ < < + > > - ] < [ > > > > > > > > . > > >
> > > > > > > > > > > > . > . > . > . > . > . > . < < < <
< < < < < < < < < < < < < < < < < < < < < < < > [ - ] > [
- ] < < [ > + > + < < - ] > [ < + > - ] + > [ < - > [ - ]
] < [ > > > > > > > > > > > > > > > > > > > > > > > > > >
> . > . > . < < < < < < < < < < < < < < < < < < < < < < <
< < < < < < < < < < < < [ - ] > > > > > > > > > > > < < <
< < - ] > > > > > < < < < < < < < < + + + < + + + + + + +
+ + + [ - ] + > > > > > > > > > > < < < < < < < < - ] > >
> > > > > > < < < < < < > [ - ] + > [ - ] < < [ > - < [ >
> + < < - ] ] > > [ < < + > > - ] < [ < + + + + + > > > >
> > < < < < < < < < < < [ < [ > > > > > > > > > > > . > >
> > > > > > > > > > > > > > > > > > > > . > . > . < < < <
< < < < < < < < < < < < < < < < < < < < < < < < < < < < <
< < - ] + > - ] + > > > > > > > > > > < < < < < - ] > > >
> > > > > + < < < < < < < < < < < < - > > > > > > > > > <
< < < < < - > > > > > > < - > > > > > - < < < < < ] + + +
+ + + + + + + > > > > - - - - - - - - - - < + < < < < - ]
+ + + + + + + + + + > > > > - - - - - - - - - - < + < < <
< - ] > > > . > > > > > > > > > > > > > > > > > > > > > >
. > . > . < < < < < < < < < < < < < < < < < < < < < < < <
2 Likes

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";
}
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…

Missing the numbers.

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)

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();
        Console.WriteLine("Please choose a language:");
        Console.WriteLine("".PadLeft(30, '='));
        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)
        {
            Console.Write("\nPlease choose: ");
            ConsoleKeyInfo tempKeyInfo = Console.ReadKey();
            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? ");
            ConsoleKeyInfo tempKeyInfo2 = Console.ReadKey();
            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? ");
            string strMaxCnt = Console.ReadLine();
            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");
        ns.Imports.Add(new CodeNamespaceImport("System"));

        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;
        fzbzCls.Members.Add(maxField);

        CodeConstructor cstr = new CodeConstructor();
        cstr.Attributes = MemberAttributes.Public;
        cstr.Parameters.Add(
                new CodeParameterDeclarationExpression(
                    new CodeTypeReference("System.Int32"), "max"));
        cstr.Statements.Add(new CodeAssignStatement(
            new CodeFieldReferenceExpression(
                new CodeThisReferenceExpression(),
                "_MaxCount"
            ), new CodeArgumentReferenceExpression("max")));
        fzbzCls.Members.Add(cstr);

        CodeMemberMethod doMeth = new CodeMemberMethod();
        doMeth.Name = "doMeth";
        doMeth.Attributes = MemberAttributes.Public;
        doMeth.ReturnType = new CodeTypeReference("System.String");
        doMeth.Parameters.Add(
            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"),
                    CodeBinaryOperatorType.Add,
                    new CodePrimitiveExpression(1)
                )
            ));

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

        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)
            ));
        ifFizzBuzz.TrueStatements.Add(
                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)
                    ));
        ifFizzBuzz.FalseStatements.Add(elseIfFizz);
        elseIfFizz.TrueStatements.Add(
                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)
                    ));
        elseIfFizz.FalseStatements.Add(elseIfBuzz);
        elseIfBuzz.TrueStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(
                        new CodeTypeReference(typeof(Console))
                    ), "WriteLine", new CodePrimitiveExpression("Buzz")
                ));
        elseIfBuzz.FalseStatements.Add(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(
                        new CodeTypeReference(typeof(Console))
                    ), "WriteLine", new CodeVariableReferenceExpression("x")
                ));

        forLooop.Statements.Add(ifFizzBuzz);
        doMeth.Statements.Add(forLooop);

        doMeth.Statements.Add(
            new CodeMethodReturnStatement(
                new CodeMethodInvokeExpression(
                    new CodeArgumentReferenceExpression("countMax"),
                    "ToString"
                )
            ));

        fzbzCls.Members.Add(doMeth);

        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..."));
        CodeMethodInvokeExpression consRead = new CodeMethodInvokeExpression(
            new CodeMethodReferenceExpression(
                new CodeTypeReferenceExpression(
                    new CodeTypeReference(typeof(Console))
                ), "ReadLine"
            ));

        CodeEntryPointMethod voidMan = new CodeEntryPointMethod();
        voidMan.Parameters.Add(new CodeParameterDeclarationExpression(
            new CodeTypeReference(typeof(object[])), "args"));
        voidMan.Statements.Add(consWrite);
        voidMan.Statements.Add(consRead);
        voidMan.Statements.Add(
            new CodeVariableDeclarationStatement(
                new CodeTypeReference("FizzBuzzOutputter"),
                "inst",
                new CodeObjectCreateExpression(
                    new CodeTypeReference("FizzBuzzOutputter"),
                    new CodePrimitiveExpression(countMax)
                )
            ));
        voidMan.Statements.Add(
            new CodeMethodInvokeExpression(
                new CodeVariableReferenceExpression("inst"),
                "doMeth",
                new CodePrimitiveExpression(countMax)
            ));
        voidMan.Statements.Add(
            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> :)
        voidMan.Statements.Add(consRead);
        progMainCls.Members.Add(voidMan);

        ns.Types.Add(progMainCls);
        ns.Types.Add(fzbzCls);

        CodeCompileUnit cdCmpUnt = new CodeCompileUnit();
        cdCmpUnt.Namespaces.Add(ns);

        // 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 outFileNm = Console.ReadLine();
        string outPath = System.IO.Path.Combine(Environment.CurrentDirectory, outFileNm);
        if (compile)
        {
            CompilerParameters compParams = new CompilerParameters();
            compParams.ReferencedAssemblies.Add("System.dll");
            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("".PadLeft(30, '='));
        Console.WriteLine("ALL DONE!  Press <Enter> to exit.");
        Console.ReadLine();

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/>";
}

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)));

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);
}

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
1 Like

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;

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

package main
import (
  "fmt"
  "github.com/someone-else-who-has-done-all-the-work-already/fizzbuzz"
)

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 !

/*
 * 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)
}

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 (add1 n)))))])
    (FB n)))

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):

(please contribute!)

Working in PHP, this is my original I got down in a minute or two:

for( $i = 1; $i < 101; $i++ )
{
    $str = "";
    $str .= ( ( $i % 3 == 0 ) ? "Fizz" : "" );
    $str .= ( ( $i % 5 == 0 ) ? "Buzz" : "" );
    $str = ( ( strlen( $str ) == 0 ) ? $i : $str );
    echo "$str\n";
}
for($i=1;$i<101;$i++){$str="";$str.=(($i%3==0)?"Fizz":"");$str.=(($i%5==0)?"Buzz":"");$str=((strlen($str)==0)?$i:$str);echo"$str\n";} // 134 chars

I then optimised it a bit:

for( $i = 1; $i < 101; $i++ )
{
    echo ( ( $i % 3 == 0 || $i %5 == 0 ) ? ( ( $i % 3 == 0 ) ? "Fizz" : "" ) . ( ( $i % 5 == 0 ) ? "Buzz" : "" ) : $i ) . "\n";
}
for($i=1;$i<101;$i++){echo($i%3==0||$i%5==0?($i%3==0?"Fizz":"").($i%5==0?"Buzz":""):$i)."\n";} // 95 chars

I wonder if a while loop could be smaller?

while( $i++ < 101 )
{
    echo ( $i % 3 == 0 || $i % 5 == 0 ? ( $i % 3 == 0 ? "Fizz" : "" ) . ( $i % 5 == 0 ? "Buzz" : "" ) : $i ) . "\n";
}
while($i++<101){echo($i%3==0||$i%5==0?($i%3==0?"Fizz":"").($i%5==0?"Buzz":""):$i)."\n";} // 89 chars

And finally, lets see if we can’t rearrange those comparisons a bit:

while( $i++ < 101 )
{
    echo ( $i % 3 == 0 ? "Fizz" . ( $i % 5 == 0 ? "Buzz" : "" ) : ( $i % 5 == 0 ? "Buzz" : $i ) ) . "\n";
}
while($i++<101){echo($i%3==0?"Fizz".($i%5==0?"Buzz":""):($i%5==0?"Buzz":$i))."\n";} // 84 chars

The two while versions raise a Notice about $i being undefined on the first loop, but it still actually runs in PHP 5.5.

I haven’t seen an R language response yet. Admittedly, I didn’t read every one of them and it’s hard to ctrl-F for R and not get a zillion responses:

    x <- seq(1, 100, 1)

    fooish <- function(x){

    y <- x
    y[x %% 3 == 0] <- "Fizz"
    y[x %% 5 == 0] <- "Buzz"
    y[x %% 15 == 0] <- "FizzBuzz"

    y <- as.data.frame(y)

    return(y)
  }

My first function was unwieldy (25 lines), took only a minute or so to write, but was successful. I went through another 15-line iteration, before finally paring it down to the 8 lines above.

Solution in Pascal. Took me more time but I am no professional just a beginner hobbyist.

var

i: integer;

Fizz, Buzz, Fizbuzz: Boolean;

begin

For i:=1 to 100 do

begin

if i mod 15 = 0 then Fizbuzz := True else Fizbuzz := False;

if i mod 3 = 0 then Fizz := True else Fizz := False;

if i mod 5 = 0 then Buzz := True else Buzz := False;

if Fizbuzz then Writeln(i, ' FIZZBUZZ')

else

begin

  if Fizz then Writeln(i, ' FIZZ');
  if Buzz then Writeln(i, ' BUZZ');

end;

if not Fizz and not Buzz then Writeln(i);

end;

end.

Real programmers program in shell scripts!

for i in {1…100}; do if [ $(($i % 3)) -eq 0 -a $(($i %5)) -eq 0 ]; then echo “FizzBuzz”; elif [ $(($i %5)) -eq 0 ]; then echo “Buzz”; elif [ $(($i % 3)) -eq 0 ]; then echo “Fizz”; else echo $i; fi; done

Or, to make it a bit more readable:

for i in {1..100}
do
    if [ $(($i % 3)) -eq 0 -a $(($i %5)) -eq 0 ]
    then
        echo "FizzBuzz"
    elif [ $(($i %3)) -eq 0 ]
    then
        echo "Fizz"
    elif [ $(($i % 5)) -eq 0 ]
    then
        echo "Buzz"
     else
        echo $i
    fi
done