a companion discussion area for blog.codinghorror.com

FizzBuzz Solution Dumping Ground


#224

I wonder why no one used this solution
no if!

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

using namespace std;

void Fizz(int &i)
{
	std::cout << "Fizz" << endl;
	i++;
}
 void Buzz(int &i)
{
	std::cout << "Buzz" << endl;
	i++;
}
int main(array<System::String ^> ^args)
{
   for (int i = 1; i < 100; i++)
	{
	         std::cout << i++ << endl;
	         std::cout << i++ << endl;
	 Fizz(i);
		  std::cout << i++ << endl;
	 Buzz(i);
	 Fizz(i);
		std::cout << i++ << endl;
		std::cout << i++ << endl;
	 Fizz(i);
	 Buzz(i);
		std::cout << i++ << endl;
	 Fizz(i);
		std::cout << i++ << endl;
		std::cout << i++ << endl;
		std::cout << "FizzBuzz" << endl;
	}
	getchar();
    return 0;
}

#225

I think this solution in C compiles down to a minimal amount of instructions.

main(){int i=0;while(++i<101)printf("%d\n\0–Fizz\n\0Buzz\n\0FizzBuzz\n"+
6*(!(i%3)+((!(i%5))*2)),i);}


#226

CodingBat code practice
Java > Array-2 > fizzBuzz

This is slightly more difficult version of the famous FizzBuzz problem which is sometimes given as a first problem for job interviews. (See also: FizzBuzz Code.) Consider the series of numbers beginning at start and running up to but not including end, so for example start=1 and end=5 gives the series 1, 2, 3, 4. Return a new String[] array containing the string form of these numbers, except for multiples of 3, use “Fizz” instead of the number, for multiples of 5 use “Buzz”, and for multiples of both 3 and 5 use “FizzBuzz”. In Java, String.valueOf(xxx) will make the String form of an int or other type. This version is a little more complicated than the usual version since you have to allocate and index into an array instead of just printing, and we vary the start/end instead of just always doing 1…100.

fizzBuzz(1, 6) → {"1", "2", "Fizz", "4", "Buzz"}
fizzBuzz(1, 8) → {"1", "2", "Fizz", "4", "Buzz", "Fizz", "7"}
fizzBuzz(1, 11) → {"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz"}
public String[] fizzBuzz(int start, int end) {
  String[] fb = new String[end - start];
  int index = 0;
  for(int i = start; i < end; i++){
  fb[index] = Integer.toString(i); //converts int to a string
  index++;
  }
  for(int p = 0; p < fb.length; p++){
  if(Integer.parseInt(fb[p]) % 3 == 0 && Integer.parseInt(fb[p]) % 5 == 0){
  fb[p] = "FizzBuzz";
  }  
  else if(Integer.parseInt(fb[p]) % 3 == 0){
  fb[p] = "Fizz";
  }
  else if(Integer.parseInt(fb[p]) % 5 == 0){
  fb[p] = "Buzz";
  }
  }
  return fb;
}

Poof, done. And I’m only a 9th grader. Though the better solution would be to replace the “multiples” of 3 and 5 or both as the array is being filled.


#227

Yeah but a loop from 1 to 10 is like easy peasy. Else you should NOT be programming.

for(int i = 1; i < 10; i++){
out.println(i);
}

#228

Why you have not corrected him from:

a=a|b, b=a^b, a=a^b

to:

a=a^b, b=a^b, a=a^b

before you hired the guy?


#229

Excessively verbose.

In Clojure you’d use (range 1 11)

In Scheme you’d use (iota 10 1)

In Smalltalk there’s 1 to: 10

Honest-to-Christ - although I’ve been programming in C and its step-children (e.g. C++, Java, C#) since 1986, these days whenever I see curly braces I just want to…ahem…look elsewhere…


#230
for ($i = 1; $i < 101; $i++) {
    if ($i % 3 == 0 && $i % 5 == 0) {
        echo 'FizzBuzz, ';
        continue;
    }

    if ($i % 5 == 0) {
        echo 'Buzz, ';
        continue;
    }

    if ($i % 3 == 0) {
        echo 'Fizz, ';
        continue;
    }

    echo $i . ', ';
}

#231

One liner here (sorry for bad spacing, but I tested and it compiled/worked on the first time):

for(int i=1;i<=100;i++)System.out.println((i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i);

If you want a string for some reason, you can probably do Integer(i).toString in place of the plain i.

To do an array, the System.out.println can be replaced with outputArray[i-1]=


#232

Shortest possible* JavaScript 1-liner:

for(var i=0;i++<100;)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i);

*yes… you should take this as a challenge :smirk:


#233

My Python solution:

 for x in range(1,101):
        if x % 3 == 0 and x % 5 == 0:
            x = "FizzBuzz"
        elif x % 3 == 0:
            x = "Fizz"
        elif x % 5 == 0:
            x = "Buzz"
        print x

#234

It was fun.

Java:

static void printFizzBuzz() {
         System.out.println("Printing FizzBuzz");
         
         int max = 100;
         
         for(int i = 0; i <= max; ++i) {
             String string = "";
             if (i % 3 == 0) {
                 string += "Fizz";
             }
             
             if (i % 5 == 0) {
                 string += "Buzz";
             }
             
             if (string.isEmpty()) {
                 string = String.valueOf(i);
             }
             
             System.out.println(string);
         }
     }

#235

A solution in C

#include<stdio.h>
#include<math.h>

void main(){

int i;

for(i=1;i<101;i++){

if(i%3==0 && i%5!=0){
printf("Fizz for i=%d\n\n",i);
}

else if(i%5==0 && i%3!=0){
printf("Buzz for i=%d\n\n",i);
}

else if(i%5==0 && i%3==0){
printf("FizzBuzz for i=%d\n\n",i);
}

else {printf("\ni=%d\n",i);}

}
}

#236

Here’s the code in Java!

public class FizzBuzz 
{
	public static void main(String[] args) 
	{
		for(int i = 1; i<101; 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);
			}
		}
	}

}

#237

I can’t take credit, but I found a Fizz Buzz solution in Piet:


#238

Here it is in Java:

public static main(String[] args) {
	System.out.println("1");
	System.out.println("2");
	System.out.println("Fizz");
	System.out.println("4");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("7");
	System.out.println("8");
	System.out.println("Fizz");
	System.out.println("Buzz");
	System.out.println("11");
	System.out.println("Fizz");
	System.out.println("13");
	System.out.println("14");
	System.out.println("FizzBuzz");
	System.out.println("16");
	System.out.println("17");
	System.out.println("Fizz");
	System.out.println("19");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("22");
	System.out.println("23");
	System.out.println("Fizz");
	System.out.println("Buzz");
	System.out.println("26");
	System.out.println("Fizz");
	System.out.println("28");
	System.out.println("29");
	System.out.println("FizzBuzz");
	System.out.println("31");
	System.out.println("32");
	System.out.println("Fizz");
	System.out.println("34");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("37");
	System.out.println("38");
	System.out.println("Fizz");
	System.out.println("Buzz");
	System.out.println("41");
	System.out.println("Fizz");
	System.out.println("43");
	System.out.println("44");
	System.out.println("FizzBuzz");
	System.out.println("46");
	System.out.println("47");
	System.out.println("Fizz");
	System.out.println("49");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("52");
	System.out.println("53");
	System.out.println("Fizz");
	System.out.println("Buzz");
	System.out.println("56");
	System.out.println("Fizz");
	System.out.println("58");
	System.out.println("59");
	System.out.println("FizzBuzz");
	System.out.println("61");
	System.out.println("62");
	System.out.println("Fizz");
	System.out.println("64");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("67");
	System.out.println("68");
	System.out.println("Fizz");
	System.out.println("Buzz");
	System.out.println("71");
	System.out.println("Fizz");
	System.out.println("73");
	System.out.println("74");
	System.out.println("FizzBuzz");
	System.out.println("76");
	System.out.println("77");
	System.out.println("Fizz");
	System.out.println("79");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("82");
	System.out.println("83");
	System.out.println("Fizz");
	System.out.println("Buzz");
	System.out.println("86");
	System.out.println("Fizz");
	System.out.println("88");
	System.out.println("89");
	System.out.println("FizzBuzz");
	System.out.println("91");
	System.out.println("92");
	System.out.println("Fizz");
	System.out.println("94");
	System.out.println("Buzz");
	System.out.println("Fizz");
	System.out.println("97");
	System.out.println("98");
	System.out.println("Fizz");
	System.out.println("100");
}

#239

PowerShell
for($i = 1;$i -le 100;$i++){

$fizz = $i % 3
$buzz = $i % 5
if($fizz -eq 0 -and $buzz -eq 0){
write-host fizzbuzz
}
if($fizz -eq 0 -and $buzz -ne 0){
write-host fizz
}
if($buzz -eq 0 -and $fizz -ne 0){
write-host buzz
}

}


#240

My weapon of choice for this problem is perl. There is such a thing as a well written perl program, but I deliberately choose to write bad code which still solves the problem.

sub _ { print /::(.*)/ }; *AUTOLOAD = *_; for(1..100) { $f=0, fizz() if 3 == ++$f; $b=0, buzz() if 5 == ++$b; $f && $b && &$_; &{" "} }

#241

Responding to a nine year old thread, because even the answers that get it right seem clunky. Couple of thoughts:

  1. Why post if you haven’t tested? Some of these answers don’t address the specs correctly, or just don’t work.

  2. Don’t be literal - elegance lies in the code you don’t write. Nearly every single answer here makes an unnecessary double-test of each condition.

  3. Stop compensating - condensing code to 1 line with 11 characters isn’t a measure of your coding prowess, it’s an indicator of the maintainability of your code. The compiler is going to reduce it all to the same IL/bytecode/machine code, so if you want hired, make the code you write at an interview readable.

In C#:

//  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”.           
    for (int i = 0; i <= 100; i++) {

        string output = (i%3 == 0) ? "Fizz" : string.Empty;

        if (i%5 == 0) {
            output += "Buzz";
        }
        
        Console.WriteLine(string.IsNullOrEmpty(output) ? i.ToString() : output);

    }
    
}

Feedback welcome.


#242

Just a small python solution, this one is generic, so you can add other factor/word tuples, if you happen to need something special to happen at multiples of 19? No problem, just add one line.

from collections import OrderedDict
rules = OrderedDict([
    (3, 'fizz'),
    (5, 'buzz'),
    (19, 'beer'),
])
for i in range(1, 101):
    output = ''
    for divisor, out in rules.items():
        if i%divisor == 0:
            output += out
    if output == '':
        output = i
    print('{}: {}'.format(i, output))

Or maybe you could even generalize your rules as lambda and evaluate them later in the loop. It would allow more complex “rules” than just a modulo operation. Of course you lose readability.

from collections import OrderedDict
rules = OrderedDict([
    ('fizz', lambda x: x%3 == 0),
    ('buzz', lambda x: x%5 == 0),
])
for i in range(1,101):
    output = ''
    for out, condition in rules.items():
        if condition(i):
            output += out
    if output == '':
        output = i
    print('{}: {}'.format(i, output))

#243

Here is my solution in PHP:

for($x = 1; $x < 100; $x++) {
if(($x % 3) && ($x % 5)) echo $x;
if(!($x % 3)) echo “Fizz”;
if(!($x % 5)) echo “Buzz”;
echo “
”;
}