FizzBuzz Solution Dumping Ground

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
}

}

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 && &$_; &{" "} }

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.

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

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 “
”;
}

in JS, king of the web
for(var i = 0; i<100; i++){
if(i % 15 === 0)
console.log(“fizzBuzz”);
else if(i % 3 === 0)
console.log(“fizz”);
else if(i % 5 === 0)
console.log(“buzz”);
else
console.log(i);
}

In Crystal, which is kind of like a compiled ruby-esque language:

Range.new(1, 100).each do |n|
  msg = ""
  if n.modulo(3) == 0
    msg = msg + "Fizz"
  end
  if n.modulo(5) == 0
    msg = msg + "Buzz"
  end
  if msg == ""
    puts n
  else 
    puts msg
  end
end

Not perfect but I just started learning the language, and the language itself isn’t production-ready.

1 Like

Haven’t seen a GAS solution yet. Well, it’s mostly just JS, but I can cheat a bit.

My first attempt just used Logger.log() and was kind of direct brute force, but worked. Though technically, I failed since, in retrospect, the Logger method doesn’t really satisfy ‘print’ from an end user perspective and the Logger ended up string converting i with 1 decimal place. Took about 2 min.

function fizzBuzz() {
  for (var i=1;i<=100;i++){
    if (i%3 == 0 && i%5 == 0){
      Logger.log('FizzBuzz');
    } else if (i%3 == 0) {
      Logger.log('Fizz');
    } else if (i%5 == 0) {
      Logger.log('Buzz');
    } else {
      Logger.log(i);
    }
  }
}

Realizing I technically failed, took an extra 5 to optimise a touch while still having it legible and output as a web app. With GAS, you can kind of cheat and provide partial HTML. It will fill in any headers and such that you’re missing, so the client side works.

Here’s the final:

function doGet() {
  var str, res = '';
  for (var i=1;i<=100;i++){
    if (i % 3 == 0) str += 'Fizz';
    if (i % 5 == 0) str += 'Buzz';
    if (!str) str = i;
    res += str + '<br>';
    str = '';
  }
  return HtmlService.createHtmlOutput(res);
}

I’m not a programmer by trade, but I do dabble in a lot of GAS (which leads to client side JS, jQuery, html, css, etc.), and (thankfully much less frequently) VBA stuff related to my job. Fairly happy with 7 minutes for a working web app that meets the goal while not technically being a programmer. And no, not cheating. Replace exec in the url with edit to see the script.

Frankly shocking to read a lot of these from people who are programmers and missed some of the basic requirements.

Just the tiniest bit disappointed to find only one PowerShell solution posted. Does no-one respect this language?
In any case, my own PS piece is a bit different so I’ll share for SnG:

$List = @(1..100)
$Fizz = 3
$Buzz = 5
ForEach ($Num In $List) {
	$Output = $Null
	If ($Num % $Fizz -EQ 0) {
		$Output += "Fizz"
	}
	If ($Num % $Buzz -EQ 0) {
		$Output += "Buzz"
	}
	If ($Output) {
		$Output
	} Else {
		$Num
	}
}

I can’t believe there isn’t any Prolog in here.


fizzBuzzPrint(A):- A mod 15 =:= 0,display(‘FizzBuzz\n’).
fizzBuzzPrint(A):- A mod 5 =:= 0,display(‘Buzz\n’).
fizzBuzzPrint(A):- A mod 3 =:= 0,display(‘Fizz\n’).
fizzBuzzPrint(A):- display(A), display(’\n’).

fizzBuzz(B,B):- fizzBuzzPrint(B).
fizzBuzz(A,B):- fizzBuzzPrint(A), C is A+1, fizzBuzz(C,B),!.

?- fizzBuzz(1,100).

PHP?
Didn’t program for ages, but heck, don’t understand why this should be difficult.
I prefer readability over short code…
I know 1) recursion takes a lot of heap, but I simply like it.
I know 2) yep, type-checking is not PHP strongest point, but heck, sometimes useful, see below…

<?php
function FizzBuzz ($n) {
 if ($n>0) {
	FizzBuzz($n-1) ;
	$fb="" ;
	if ($n%3==0) { $fb = "Fizz" ; }
	if ($n%5==0) { $fb .= "Buzz" ; }
	$fb = ($fb=="") ? $n : $fb ;
	echo $fb."\n" ;
 }
}

FizzBuzz (100) ;
?>

and not a comment in any of them… you’re all fired.

Can I have a retry pls dear manager…

<?php
function FizzBuzz ($n) {

// Define the array with dividers and what to shout
 $match = array (3 => "Fizz", 5 => "Buzz", 7 => "Woof", 11 => "Waf" ) ;
 if ($n>0) {
        // Recursively call FizzBuzz when $n > 0
	FizzBuzz($n-1) ;
        // $fb defines what to shout
	$fb="" ;
        // Cycle through the $match array and if we found a match add it to the output.
	foreach ( $match as $div => $shout) if ($n%$div == 0) $fb .= $shout ;
	$fb = ($fb=="") ? $n : $fb ; // If there is nothing to shout show the number
	echo $fb."\n" ;
        // FizzBuzz($n-1) ; // Put FizzBuzz here if you want it in reverse order
 }
}

FizzBuzz (100) ;
?>

It’s wrong. No “Echo i” here

It’s been a while since I’ve used python but you seem to have confused return and print. I don’t think this will output anything outside of the interpreter.

Unless I’m missing something this is really easy, I didn’t think about it very hard.

using System;
namespace fizzbuzz {
    class Program {
        static void Main(string[] args) {
            for (int i = 1; i < 101; i++) {
                if (i % 3 == 0) Console.Write("Fizz");
                if (i % 5 == 0) Console.Write("Buzz");
                if (i % 3 != 0 && i % 5 != 0) Console.Write(i);
                Console.WriteLine("");
            }
            Console.Read();
        }
    }
}

Just ran across this article… So, I decided to share the scary one. My PAINFUL submission is:

Applesoft Basic

Yes, you heard that right! I am writing this in APPLESOFT BASIC.

10 I = 0
15 E = 100
20 I = I + 1
30 IF ((I/15) >< INT(I/15)) THEN 40
35 PRINT "FizzBuzz"
38 IF I < E THEN 20
39 IF I = E THEN 80
40 IF ((I/5) >< INT(I/5)) THEN 50
45 PRINT "Buzz"
48 IF I < E THEN 20
49 IF I = E THEN 80
50 IF ((I/3) >< INT(I/3)) THEN 60
55 PRINT "Fizz"
58 IF I < E THEN 20
59 IF I = E THEN 80
60 Print I
70 IF I < E THEN 20
80 END

You can check my code at:
http://www.calormen.com/jsbasic/

And then you can program in APPLESOFT BASIC also.

Now, are you in pain yet??? I know I am.

Drat… I am breaking all the rules here…

Does your reply improve the conversation in some way? - It is APPLESOFT BASIC! So, no…

Be kind to your fellow community members. - I am posting APPLESOFT BASIC… so no…

Constructive criticism is welcome, but criticize ideas, not people. - I am sure APPLESOFT BASIC still breaches this one also…

1 Like

I like matlab. This is 81 character.

k=num2cell(1:100);k(3:3:99)={'Fizz'};k(5:5:100)={'Buzz'};k(15:15:90)={'FizzBuzz'}

To show the fizzBuzz you should write the if (((i % 5) == 0) && ((i % 3) == 0)) at the top of the conditions list.
otherwise, it will not display the fizzbuzz, that’s logic :slight_smile:

C# code:

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 100; i++) {
                
                   if (((i % 5) == 0) && ((i % 3) == 0))
                    {
                        Console.WriteLine("fizz Wizz");
                    }
                   else  if ((i % 3) == 0)
                    {
                        Console.WriteLine("fizz");
                    }
                    else if ((i % 5) == 0)
                    {
                        Console.WriteLine("Wizz");
                    }
                    else
                    Console.WriteLine(i);
                
            }
            Console.ReadLine();
        }
    }
    for(int i=0; i<=100; i++){
            if ( i%3==0 || i%5==0){
                    if( i % 3 == 0 ) printf("Fizz");
                    if( i % 5 == 0 ) printf("Buzz");
            }
            else printf("%d",i);
            printf("\n");
    }