a companion discussion area for blog.codinghorror.com

FizzBuzz Solution Dumping Ground


#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"
  "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 !


#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 (add1 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):

(please contribute!)


#209

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.


#210

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.


#211

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.


#212

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

#213

Had to join in the fun :stuck_out_tongue_winking_eye:

import java.lang.*;

public class fizzbuzz {

private static final String output[] = {"%d","Fizz","Buzz","FizzBuzz"};

public static void main(String[] args) {
 for(int i=1; i<101; i++) {
    int item = ((i % 3) == 0 ? 2 : 0) + ((i % 5) == 0 ? 1 : 0);
    System.out.println(String.format(output[item],i));
  }
 }
}

#214

Solution I had to do today during a skype interview :smile:

public class FizzBuzz {
    public static void main(String[] args) {
        for (int number = 1; number < 101; number++) {
            boolean dividableBy3 = number % 3 == 0;
            boolean dividableBy5 = number % 5 == 0;

            if (dividableBy3 && dividableBy5) {
                System.out.println("FizzBuzz");
            } else if (dividableBy5) {
                System.out.println("Buzz");
            } else if (dividableBy3) {
                System.out.println("Fizz");
            } else {
                System.out.println(number);
            }
        }
    }
}

#215

postgresql

select case 
   when a%15=0 then 'Fizzbuzz'
   when a%3=0  then 'Fizz'
   when a%5=0  then 'Buzz'
   else a::text end 
from generate_series(1,100) as a;

#216

C++

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main()
{
    char buffer[33];

    for (int i = 1; i <= 100; i++)
    {
        cout << (i % 3 == 0 ? "Fizz" : "");
        cout << (i % 5 == 0 ? "Fuzz" : "");
        cout << (i % 3 != 0 && i % 5 != 0 ? itoa(i, buffer, 10) : "");
        cout << endl;
    }

    getchar();

    return 0;
}

#217

C++ recursive

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

char buffer[33];

void fizzfuzz(int i)
{
	if (i == 0) return;

	fizzfuzz(i - 1);

        cout << (i % 3 == 0 ? "Fizz" : "");
        cout << (i % 5 == 0 ? "Fuzz" : "");
        cout << (i % 3 != 0 && i % 5 != 0 ? itoa(i, buffer, 10) : "");
        cout << endl;
}

int main()
{
	fizzfuzz(100);

	getchar();

	return 0;
}

and without buildup

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

char buffer[33];

void fizzfuzz(int limit);

void fizzfuzz(int i, int limit)
{
    if (i == limit) return;

    cout << (i % 3 == 0 ? "Fizz" : "");
    cout << (i % 5 == 0 ? "Fuzz" : "");
    cout << (i % 3 != 0 && i % 5 != 0 ? itoa(i, buffer, 10) : "");
    cout << endl;

    fizzfuzz(i + 1, limit);
}

void fizzfuzz(int limit)
{
    fizzfuzz(1, limit);
}

int main()
{
    fizzfuzz(100);

    getchar();

    return 0;
}

#218

OK, just for fun let’s do this in Clojure (a Lisp variant that runs on the JVM):

(map #(cond
        (= 0 (mod % 3) (mod % 5)) "FizzBuzz"
        (= 0 (mod % 3)) "Fizz"
        (= 0 (mod % 5)) "Buzz"
        :else %) (range 1 101))

OR - how about PL/SQL (Oracle’s bastard stepchild of Ada + embedded SQL)?

BEGIN
  FOR i IN 1..100 LOOP
    IF MOD(i, 3) = 0 AND MOD(i, 5) = 0 THEN
      DBMS_OUTPUT.PUT_LINE('FizzBuzz');
    ELSIF MOD(i, 3) = 0 THEN
      DBMS_OUTPUT.PUT_LINE('Fizz');
    ELSIF MOD(i, 5) = 0 THEN
      DBMS_OUTPUT.PUT_LINE('Buzz');
    ELSE
      DBMS_OUTPUT.PUT_LINE(i);
    END IF;
  END LOOP;
END;

#219

C# console app, with a little extra flexibility to specify the range, configure the numbers and words, and easily swap in different trigger logic.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var wordParameters = new Dictionary<int, string> 
                                    {
                                        { 3, "Fizz" },
                                        { 5, "Buzz" }
                                    };

            Func<int, Dictionary<int, string>, string> lineAuthor = (i, divWords) =>
            {
                string words = String.Join(String.Empty,
                                        divWords
                                            .Keys
                                            .Where(k => i % k == 0)
                                            .Select(k => divWords[k])
                                            .ToArray());

                return String.IsNullOrWhiteSpace(words) ? i.ToString() : words;
            };

            Run(1, 100, wordParameters, lineAuthor);

            Console.ReadLine();
        }

        private static void Run(int startValue, int endValue,
            Dictionary<int, string> wordParameters,
            Func<int, Dictionary<int, string>, string> lineAuthor)
        {
            for (int k = startValue; k <= endValue; k++)
            {
                Console.WriteLine(lineAuthor(k, wordParameters));
            }
        }
    }
}

#220

class Main {
public static void main(String[] args) {
for(int i=1; i<=100; i++)
{
if(i%3==0 && i%5==0)
{
System.out.println(“FizzBuzz”);
}
else if(i%3==0)
{
System.out.println(“Fizz”);
}
else if(i%5==0)
{
System.out.println(“Buzz”);
}
else
{
System.out.println(i);
}
}
}
}


#221

int main(){

for(int i=1; i<=100;i++)
{

if((i%3==0)&&(i%5==0)){
 cout << "fizzBuzz" <<endl;
}
else if(i%5==0){
 cout << "Buzz" <<endl;
}
else if(i%3==0){
 cout << "Fizz" <<endl;
}else{cout << i << endl;}

}

system(“PAUSE”);
return 0;
}


#222

This is probably not the best use of my time, but I wanted to try this out in AutoHotkey script.

Loop 100
{
  If i =
    i = %A_Index%
  Else
  {
    If % Mod(A_Index,3) = 0 and Mod(A_Index,5) = 0
      i = %i%,FizzBuzz
    If % Mod(A_Index,3) = 0
      i = %i%,Fizz
    If % Mod(A_Index,5) = 0
      i = %i%,Buzz
    Else
      i = %i%,%A_Index%
  }
}
MsgBox %i%

#223

public static void main(String[] args) {

int i;


    for (i=0; i<=100; i++){
        
        if (i%3==0&&i%5!=0){            //the && i%5!=0 is so it does not enter here if its a FizzBuzz
            System.out.println("Fizz");
        
        }
        if (i%5==0&&i%3!=0){            //the && i%3!=0 is so it does not enter here if its a FizzBuzz
            System.out.println("Buzz");
        
        }
        if (i%5==0&&i%3==0){            //Two conditions apply so it gives FizzBuzz
            System.out.println("FizzBuzz");
        }
        if (i%5!=0&&i%3!=0){            //For Everything Else
            System.out.println(i);
        }
    }
}

}