FizzBuzz Solution Dumping Ground

Matthew,

In your perl version, you could have done this, to be more perlish of course… (I prefer readability/cleanliness/maintainability, hence I use python).

instead of:

$out .= (($i % 3) == 0) ? “fizz” : “”;

you could just use:

$out .= (!($i%3)) ? “fizz” : “”;

This response is only to point out the above, I’m not criticising or ‘correcting’ anything… just pointing out that in perl as with other languages doing a simple NOT operand removes unnecessary right side evaluation operators. The thing that bothers me still about perl is that in my solution, the ratio of punctuation vs. alphanumerics is greater than 2:1 $.=(!($%))?"":""; : out3fizz

For the guy who wrote the “executable line noise” Perl version: I’m glad you program in Python.

use strict;
use warnings;

for my $i (1…100) {
my $div3 = $i % 3 == 0;
my $div5 = $i % 5 == 0;
if ( $div3 and $div5 ) {
print ‘fizzbuzz’;
}
elsif ($div3) {
print ‘fizz’;
}
elsif ($div5) {
print ‘buzz’;
}
else {
print $i;
}
print “\n”;
}

It’s not clever, but I’ll be able to read it easily 6 months or a year later.

If you insist on the ternary operator, try this:

for my $i (1…100) {
my $div3 = $i % 3 == 0;
my $div5 = $i % 5 == 0;
print +($div3 and $div5) ? ‘fizzbuzz’ :
$div3 ? ‘fizz’ :
$div5 ? ‘buzz’ :
$i;
print “\n”;
}

My MS SQL Solution…(im a newbie programmer, so its probably not the most efficent solution!)

declare @i int
declare @text varchar(50)
declare @i3 int
declare @i5 int

set @i=1

while @i = 1000
begin
set @text = ''
set @i3 = @i/3
set @i5 = @i/5

	if (@i3*3=@i) and (@i5*5@i)
		begin
		set @text = 'Fizz'
		end
	if (@i3*3@i) and (@i5*5=@i)
		begin
		set @text = 'Buzz'
		end
	if (@i3*3=@i) and (@i5*5=@i)
		begin
		set @text = 'FizzBuzz'
		end
			
	print convert(varchar(5),@i) + ' - ' + @text 

	set @i = @i + 1
end

Any comments id be grateful - MattConway@GMail.com

Yeah, I can write a Sieve of Eratosthenes, but why are you only sifting out two primes? Well, you ask a silly question, you get a silly answer. We don’t even need looping or conditional statements for this one.

print 1
print 2
print "Fizz"
print 4
print "Buzz"
print "Fizz"
print 7
print 8
…etc, etc.

?php
for ($i=1; $i = 100; $i++) {
echo $i;
if ($i%3 == 0) {
echo " fizz";
}
if ($i%5 == 0) {
echo " buzz";
}
echo “br /”;
}
?

netron:

Actually, that’s a pretty inefficient way to do it.

Bah, was going to explain, but writing code’ll be easier:

public int GetLargestSequence(string input)
{
int largest = count = 1;
char largestChar = input[0];

        for (int i = 1; i  input.Length; i++)
        {
            if (input[i] != input[i - 1])
            {
                if (count  largest)
                {
                    largest = count;
                    largestChar = input[i - 1];
                }

                count = 0;
            }

            count++;
        }
    }

Should work anyway, not tested… web forms don’t compile well. :wink: No need to keep a bunch of string arrays around when you’re just counting something.

My first attempt:

(1…100).each do |i| puts i % 3 == 0 ? (i % 5 == 0 ? “FizzBuzz” : “Fizz”) : (i % 5 == 0 ? “Buzz” : i) end

It’s ugly, but the whole point was your first non-tested ‘on the paper’ result :slight_smile:

mtrpcic: Yeah, it is… but yours is wrong also since the spec was 1 to 100, not 0 to 99.

The definitive C++ solution:

#include iostream

template int n, int m3, int m5
struct fizzbuzz
{
fizzbuzzn-1, (n-1)%3, (n-1)%5 fb;
fizzbuzz()
{ std::cout n std::endl; }
};

template int n
struct fizzbuzzn, 0, 0
{
fizzbuzzn-1, (n-1)%3, (n-1)%5 fb;
fizzbuzz()
{ std::cout “FizzBuzz” std::endl; }
};

template int n, int p
struct fizzbuzzn, 0, p
{
fizzbuzzn-1, (n-1)%3, (n-1)%5 fb;
fizzbuzz()
{ std::cout “Fizz” std::endl; }
};

template int n, int p
struct fizzbuzzn, p, 0
{
fizzbuzzn-1, (n-1)%3, (n-1)%5 fb;
fizzbuzz()
{ std::cout “Buzz” std::endl; }
};

template
struct fizzbuzz0,0,0
{
fizzbuzz()
{ std::cout 0 std::endl; }
};

template int n
struct fb_run
{
fizzbuzzn, n%3, n%5 fb;
};

int main()
{
fb_run100 fb;
}

It may be a bit long.

Uh, someone ordered an x86 assembly version?

(Linux Syscalls/NASM/ELF)

%macro write 2
; Argument 0: char* string to write
; Argument 1: length of string
mov edx, %2 ; edx = length
mov ecx, %1 ; ecx = string
mov ebx, 1 ; ebx = “stdout” stream
mov eax, 4 ; eax = "WRITE"
int 0x80 ; Linux syscall
%endmacro

section .rodata

section .bss

i: resb 1
c: resb 1
tmp: resb 1

section .text

global _start
_start:
mov byte [i], 1
forloop:
cmp byte [i], 100
jbe not_exit
jmp exit
not_exit:

    ; if (i % 3 == 0)
    mov al, [i]
    xor ah, ah
    mov cl, 3
    div cl
    test ah, ah
    jnz trybuzz
        write FIZZ, 4
        ; if (i % 5 == 0)
        mov al, [i]
        mov cl, 5
        div cl
        test ah, ah
        jnz not_buzz
            write BUZZ, 4

not_buzz:
jmp continue
trybuzz:
; if (i % 5 == 0)
mov al, [i]
xor ah, ah
mov cl, 5
div cl
test ah, ah
jnz printnum
write BUZZ, 4
jmp continue
printnum:
; Write the number i
mov al, [i]
xor ah, ah
cmp al, 100
jl tens
mov cl, 100
div cl ; ah = al % 100
add al, '0’
mov [c], al
mov [tmp], ah
write c, 1
mov al, [tmp]
xor ah, ah
tens:
mov al, [i]
cmp al, 10
jl ones
mov cl, 10
div cl ; ah = al % 10
add al, '0’
mov [c], al
mov [tmp], ah
write c, 1
mov al, [tmp]
xor ah, ah
ones:
add al, '0’
mov [c], al
write c, 1
continue:
write NL, 1

    inc byte [i]
jmp forloop

exit:
mov ebx, 0
mov eax, 1
int 0x80

; OH MY GOD THAT TOOK AGES!!!

3 Likes

R. Butler: There’s a typo in the code you refer to (by the original poster of that code).

The actual swap logic uses only XOR:

A = 5
B = 10

A = A XOR B // A == 15, B == 10
B = B XOR A // A == 15, B == 5
A = A XOR B // A == 10, B == 5

As you can see, the swap does occur. :slight_smile:

public abstract class Factory
{
    public string ToString(char[] chars)
    {
        return new string(chars);
    }
}

public class FizzFactory : Factory
{
    private const char F = 'F';
    private const char i = 'i';
    private const char z = 'z';

    public bool isFizz(int input)
    {
        if (input == 3) return true;
        else if (input == 6) return true;
        else if (input == 9) return true;
        else if (input == 12) return true;
        else if (input == 15) return true;
        else if (input == 18) return true;
        else if (input == 21) return true;
        else if (input == 24) return true;
        else if (input == 28) return true;
        else if (input == 30) return true;
        else if (input == 33) return true;
        else if (input == 36) return true;
        else if (input == 39) return true;
        else if (input == 42) return true;
        else if (input == 45) return true;
        else if (input == 48) return true;
        else if (input == 51) return true;
        else if (input == 54) return true;
        else if (input == 57) return true;
        else if (input == 60) return true;
        else if (input == 63) return true;
        else if (input == 66) return true;
        else if (input == 69) return true;
        else if (input == 72) return true;
        else if (input == 75) return true;
        else if (input == 78) return true;
        else if (input == 81) return true;
        else if (input == 84) return true;
        else if (input == 87) return true;
        else if (input == 90) return true;
        else if (input == 93) return true;
        else if (input == 96) return true;
        else if (input == 99) return true;
        else return false;
    }

    public string GetFizz()
    {
        return base.ToString(new char[4] { F, i, z, z });
    }
}

public class BuzzFactory : Factory
{
    private const char B = 'B';
    private const char u = 'u';
    private const char z = 'z';

    public bool isBuzz(int input)
    {
        if (input == 5) return true;
        else if (input == 10) return true;
        else if (input == 15) return true;
        else if (input == 20) return true;
        else if (input == 25) return true;
        else if (input == 30) return true;
        else if (input == 35) return true;
        else if (input == 40) return true;
        else if (input == 45) return true;
        else if (input == 50) return true;
        else if (input == 55) return true;
        else if (input == 60) return true;
        else if (input == 65) return true;
        else if (input == 70) return true;
        else if (input == 75) return true;
        else if (input == 80) return true;
        else if (input == 85) return true;
        else if (input == 90) return true;
        else if (input == 95) return true;
        else if (input == 100) return true;
        else return false;
    }

    public string GetBuzz()
    {
        return base.ToString(new char[4] { B, u, z, z });
    }
}

public delegate void FizzBuzzWriter(string input);
public class Looper
{
    private FizzFactory Fizz;
    private BuzzFactory Buzz;
    public event FizzBuzzWriter OnFizzBuzz;

    public Looper(Factory fizzFact, Factory buzzFact)
    {
        Fizz = (FizzFactory) fizzFact;
        Buzz = (BuzzFactory) buzzFact;
    }

    public void execute(int start, int finish)
    {
        for(int i = start; i=finish; i++)
        {
            string val = String.Empty;
            if (Fizz.isFizz(i)) val += Fizz.GetFizz();
            if (Buzz.isBuzz(i)) val += Buzz.GetBuzz();
            if (val == String.Empty) val = i.ToString();

            if (OnFizzBuzz != null) OnFizzBuzz(val);
        }
    }

}

public class TheFizzBuzzProgram
{
    public static void main(string[] args)
    {
        Looper l = new Looper(new FizzFactory(), new BuzzFactory());
        l.OnFizzBuzz += new FizzBuzzWriter(l_OnFizzBuzz);
        l.execute(1,100);
    }

    static void l_OnFizzBuzz(string input)
    {
        Console.Write(input + Environment.NewLine);
    }
}

I wrote this in C++ …it compile right and seemed output to the screen correctly. I’m no computer programmer, I just fiddle around with stuff.

I timed myself it took 25 to 30 minutes.

#include iostream
using namespace std;
int main()
{
int counter = 1;
int three;
int five;
while(counter 101)
{
three = counter % 3;
five = counter % 5;

if(three == 0  five == 0)
{
         cout  "FizzBuzz"  endl;
         }
if (three != 0  five != 0)
{
          cout  counter  endl;
          }
if (three == 0  five != 0)
{
          cout  "Fizz"  endl;
          }
if (three != 0  five == 0)
{
          cout  "Buzz"  endl;
          }
counter++;

}
system(“PAUSE”);
}

gcc actually compiles more efficient code when using a temp variable than it does if you use the xor trick.

— swap.s Sun Feb 25 02:06:34 2007
+++ xor-swap.s Sun Feb 25 02:05:52 2007
@@ -24,9 +24,12 @@
call gets
movl %eax, (%esp)
call atoi

  •   orl     %eax, %ebx
      addl    $12, %esp
    
  •   pushl   %ebx
    
  •   xorl    %ebx, %eax
      pushl   %eax
    
  •   xorl    %eax, %ebx
    
  •   pushl   %ebx
      pushl   $.LC0
      call    printf
      leal    -8(%ebp), %esp
    

The xor thing is one little antique trick which is completely and utterly pointless to ask about in an interview.

Actually I got asked a really simple question the last interview I had: given two rectangles in space, how do you test whether they overlap? I faltered for a moment, and remarked that I’d never actually done that before and had no idea how to do it. Then I got a piece of paper and did it. Really easy of course, but I think the interviewers got more information out of that than if I had automatically known how to do it.

Anyway, FizzBuzz is an ideal problem in which to be clever and use goto!

Sorry I can’t resist.

for(int i = 1; i = 100; ++i)
{
if(i % 3 == 0) { std::cout “Fizz”; goto fizzbuzz_newline; }
if(i % 5 == 0) { std::cout “Buzz”; goto fizzbuzz_newline; }
std::cout i;
fizzbuzz_newline:
std::cout endl;
}

Unless you want the object-oriented C++ version:
http://interreality.org/~reed/tmp/fb.cc

I say, all the fucking better. The more shitty programmers there are out there in the world, the more in-demand us programmers that can actually think are. I say, let 99% of the programmers be dullards, so they can pay their salaries to me!

By the way, that algorithm can be written in like 9 lines:

for( int i=1; i101; 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 );

DONE! Java all.

for (int i=1; i = 100; i++) {
Console.WriteLine(new object[] { “FizzBuzz”, “Fizz”, “Buzz”, i}
[“033132133123133”[i % 15]-‘0’]);
}

couldn’t help myself, a one liner in php

while($a101){ echo (($a%3)!=0) ? $a."\n" : “Fizz\n”; $a++;}

Cheers

for (int i=1; i = 100; i++) {
Console.WriteLine(new object[] { “FizzBuzz”, “Fizz”, “Buzz”, i}
[“033132133123133”[i % 15]-‘0’]);
}

There is very much truth to what you said. Don’t know about the “statistics” you present, but real-world proficiency seems to be a problem in many fields. In any case, here’s my two cents in about three minutes (not the only way, I know). It is HTML for the purpose of presenting HTML (hence the commented code):

!–
html
head
/head
script
for (i = 1; i = 100; i++) {
switch (i%15){
case 0:
document.writeln(“FizzBuzzbr/”);
break;
case 5:
document.writeln(“Buzzbr/”);
break;
case 10:
document.writeln(“Buzzbr/”);
break;
case 3:
document.writeln(“Fizzbr/”);
break;
case 6:
document.writeln(“Fizzbr/”);
break;
case 9:
document.writeln(“Fizzbr/”);
break;
case 12:
document.writeln(“Fizzbr/”);
break;
default:
document.writeln(i + “br/”);
break;
}
}
/script
/html

Thanks for the observations and insight :slight_smile:

I’m lame for even posting this…

Java. 5 min. Including testing. For production code I’d bother with comments and even a lame test case. Suck on it.

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