a companion discussion area for blog.codinghorror.com

FizzBuzz Solution Dumping Ground


#121

sorry for the previous posts :s

print(substr(fread($f=fopen(‘http://golf.shinh.org/p.rb?FizzBuzz’,'r’),2243),1721,522));fclose($f);


#122

I had a 2 semester course in graduate school called “Natural Language Processing” which focused on compiler and writing compilers. This course was amazing and I have been using the same routines for a wide variety of applications for years. The most handy tools techniques were parsing, recursion, multiple linked lists and trees. Enclosed is bit of code that is a real test of reading code with recursion. The code is used to balance an existing binary tree. Enjoy…

#include stdio.h

typedef struct treenode
{
struct treenode *left;
struct treenode *right;
} TREENODE;

static int list_num;
static TREENODE list_base;
static TREENODE *list_tail;
static TREENODE *root;
static int left;

void *balance( void *old_root );

static void list_build( TREENODE *node );
static TREENODE *form_tree( int );

void *balance( void *old_root )
{
if( old_root == NULL ) return( NULL );

list_tail = list_base;
list_num = 0;
list_build( old_root );

root = list_base.right;

left = 0;

return( (void *)form_tree( list_num ) );
}

static TREENODE *form_tree( int num )
{
int middle;
TREENODE *ptr;

middle = ( num 1 );

if( num == 5 ) middle++;
if( left ) middle = num - middle - 1;
left = 1;
ptr = ( middle 0 ) ? form_tree( middle ) : NULL;
root-left = ptr;
ptr = root;
root = root-right;
left = 0;
middle = num - middle - 1;
ptr-right = ( middle 0 ) ? form_tree( middle ) : NULL;
return( ptr );
}

static void list_build( TREENODE *node )
{
if( node-left ) list_build( node-left );
list_tail-right = node;
list_tail = node;
list_num++;
if( node-right ) list_build( node-right );
}


#123

Though I full well understand the intent of this article, I saw the TinyMUSH solution and decided to write one up in MUCK Forth.

: tell
me @ swap notify
;
: main
1 begin dup 101 while
dup 15 % if dup 5 % if dup 3 % if dup intostr else “Fizz” then else “Buzz” then else “FizzBuzz” then tell 1 +
repeat
;


#124
Sub Main()

    For n As Single = 1 To 100

        Select Case True
            Case n Mod 15 = 0
                Console.WriteLine("FizzBuzz")

            Case n Mod 3 = 0
                Console.WriteLine("Fizz")

            Case n Mod 5 = 0
                Console.WriteLine("Buzz")

            Case Else
                Console.WriteLine(n)

        End Select

    Next n

End Sub

#125

Yes, later i see the problem… first must check if it is multiple of 3 and multiple of 5…because if it is multiple of both wend it first check for i%3 it will write just Fizz, there is the right code:

for (int i=0; i101; i++)
{
if (i%5==0 i%3==0)//Print if is multiple of 3 AND 5 print
//Fizzbuzz and not the #
{
cout “Fizzbuzz”;
}
else//not multiple of 3 and 5… then print the number
{
if (i%3==0)//Print if is multiple of 3 print Buzz and not the #
{
cout “Fizz”;
}
else//not multiple of 3
{
if (i%5==0)//Print if is multiple of 5 print Buzz and not the #
{
cout “Buzz”;
}
else//not multiple of 5 or 3
{//print the number only if not multiple of 3 anf/or 5
cout i;
}
}//end if of multiple of 3
}//end if of multiple of 3 and 5
cout"\n"; //just endline for every case
}

Thanks… it works for C++, Java or C# just change the COUT lines for the output


#126

I thought I would try for the most complex solution :slight_smile:

class CIntegerMod3;
class CIntegerMod5;
class CIntegerMod3andMod5;

class CInteger
{
public:
static CInteger* Create( const int value )
{
CInteger* pInteger = NULL;

    if( ( value % 3 == 0 )  ( value % 5 == 0 ) )
    {
        pInteger = new CIntegerMod3andMod5( value );
    }
    else if( value % 3 == 0 )
    {
        pInteger = new CIntegerMod3( value );
    }
    else if( value % 5 == 0 )
    {
        pInteger = new CIntegerMod5( value );
    }
    else
    {
        pInteger = new CInteger( value );
    }

    return pInteger;
}

static void Delete( CInteger* pInteger )
{
    if( pInteger )
    {
        delete pInteger;
    }
}

virtual void Print( void ) const
{
    cout  m_Value  '\n';
}

protected:
CInteger( const int value )
{
m_Value = value;
}

~CInteger( void )
{
};

int m_Value;

};

class CIntegerMod3 : public CInteger
{
public:
virtual void Print( void ) const
{
cout “Fizz\n”;
}
};

class CIntegerMod5 : public CInteger
{
public:
virtual void Print( void ) const
{
cout “Buzz\n”;
}
};

class CIntegerMod3andMod5 : public CInteger
{
public:
virtual void Print( void ) const
{
cout “FizzBuzz\n”;
}
};

void PrintNumbers( void )
{
for( int i = 0; i = 100; ++i )
{
CInteger* pInteger = CInteger::Create( i );

    if( pInteger )
    {
        pInteger-Print();
        CInteger::Delete( pInteger );
    }
}

}

Cheers


#127

.NET version (minute and thirty seconds):
for (int x = 1; x 101; x++)
{
bool Wrote = false;
if (x % 3 == 0)
{
Console.Write(“Fizz”);
Wrote = true;
}
if (x % 5 == 0)
{
Console.Write(“Bizz”);
Wrote = true;
}
if(!Wrote)
{
Console.Write(x.ToString());
}
Console.Write("\n");
}


#128

Python

for i in range(1, 100) :
fmt = [i, “fizz”, “buzz”, “fizz buzz”]
print fmt[(i % 3 == 0) + 2 * (i % 5 == 0)]


#129

I mainly program in Visual Basic.
My solution for the FizzBuzz question would be:
Option Explicit

Private Sub Form_Load()
Dim intCount As Integer
Dim blnFizzBuzz As Boolean

For intCount = 1 To 100
  If int_Teller Mod 3 = 0 Then
    txtResult.Text = txtResult.Text  "Fizz"
    blnFizzBuzz = True
  End If
  If intCount Mod 5 = 0 Then
    txtResult.Text = txtResult.Text  "Buzz"
    blnFizzBuzz = True
  End If
  If Not blnFizzBuzz Then
    txtResult.Text = txtResult.Text  int_Teller
  End If
  txtResult.Text = txtResult.Text  vbCrLf
  blnFizzBuzz = False
Next intCount

End Sub

To swap two strings without temp var I’d use this:
Dim String1 As String
Dim String2 As String

String1 = String1 String2
String2 = Left(String1, Len(String1) - Len(String2))
String1 = Right(String1, Len(String1) - Len(String2))

I guess we’re all somehow work enslaved idiots :wink: posting these solutions here because that never was the question.


#130

ECMAScript Solution:

function fizzBuzz(lim) { var msg=’’; for (var i=1; ilim+1; i++) msg += (i%3==0 i%7==0?‘FizzBuzz’:(i%3==0?‘Fizz’:(i%7==0?‘Buzz’:i)))+’ '; return msg; }


#131

Oh, boy. You write an insightful post and we all jump on the code quiz. You knew someone would have to write this in MSIL, right?

.assembly extern mscorlib {}
.assembly fizzbuzz {.ver 1:0:1:0}
.module fizzbuzz.exe
.method static void main() cil managed
{
.entrypoint
.maxstack 2
.locals init (
[0] int32 num,
[1] bool divisibleByThree,
[2] bool divisibleByFive)

//initialize counter
    ldc.i4.1 
    stloc.0 

br.s _checkEndCondition

_beginLoop: 
	//Check divisible by three
	ldloc.0 
    ldc.i4.3 
    rem 
    ldc.i4.0 
    ceq 
    stloc.1 

	//Check divisible by five
    ldloc.0 
    ldc.i4.5 
    rem 
    ldc.i4.0 
    ceq 
    stloc.2 

	//Check if not divisible by three or five
	ldloc.1 
	brtrue.s _checkDivisibleByThree
	ldloc.2 
	brtrue.s _checkDivisibleByThree
	
	//Not divisible by three or five, write counter
	ldloc.0 
	call void [mscorlib]System.Console::WriteLine(int32)
	br.s _incrementCounter
	
_checkDivisibleByThree: 
	ldloc.1 
    brfalse.s _checkDivisibleByFive
    ldstr "Fizz"
    call void [mscorlib]System.Console::Write(string)

_checkDivisibleByFive:
    ldloc.2 
    brfalse.s _newLine
	ldstr "Buzz"
	call void [mscorlib]System.Console::Write(string)

_newLine:
	call void [mscorlib]System.Console::WriteLine()

_incrementCounter: 
	ldloc.0 
    ldc.i4.1 
    add 
    stloc.0 

_checkEndCondition: ldloc.0 
    ldc.i4.s 0x65
    blt.s _beginLoop
ret 

}


#132

Unfortunately, no HTML seemingly means no XSLT… tsss.
This program should be run on itself :wink: and of course the square brackets shouldn’t be more angular. let’s hope this passes the filter then…

[?xml version=“1.0” encoding=“utf-8”?]
[xsl:stylesheet version=“1.0” xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”]
[xsl:output method=“text”/]
[xsl:template name=“fizzbuzz” match="/"]
[xsl:param name=“n” select=“1”/]
[xsl:param name=“maxN” select=“100”/]
[xsl:choose]
[xsl:when test ="$n mod 15 = 0"]FizzBuzz[/xsl:when]
[xsl:when test ="$n mod 5 = 0"]Buzz[/xsl:when]
[xsl:when test ="$n mod 3 = 0"]Fizz[/xsl:when]
[xsl:otherwise]
[xsl:value-of select="$n"/]
[/xsl:otherwise]
[/xsl:choose]
[xsl:text]
[/xsl:text]
[xsl:if test="$n $maxN"]
[xsl:call-template name=“fizzbuzz”]
[xsl:with-param name=“n” select="$n + 1"/]
[/xsl:call-template]
[/xsl:if]
[/xsl:template]
[/xsl:stylesheet]


#133

Java Recursive Implementation

public class Fizz
{
public static String fizzbuzz(int i)
{
if (i == 0) return “”;
if ((i%3 == 0) (i%5 == 0)) return fizzbuzz(i-1)+“FizzBuzz\n”;
if (i%3 == 0) return fizzbuzz(i-1)+“Fizz\n”;
if (i%5 == 0) return fizzbuzz(i-1)+“Buzz\n”;

	return fizzbuzz(i-1)+i+"\n";
}

public static void main(String[] args)
{
	System.out.println(fizzbuzz(100));
}

}


#134

Javascript fizzBuzz

for(var i=1;i=100; i++) {
if((i%3==0) (i%5==0)) document.write(“FizzBuzzBR”);
else if(i%3==0) document.write(“FizzBR”);
else if(i%5==0) document.write(“Buzzbr”);
else document.write(i +“br”);
}


#135

In PostgreSQL:

select i,case when i % 3 = 0 then ‘Fizz’ end,case when i % 5 = 0 then ‘Buzz’ end from generate_series(1,100) v(i);


#136

Javascript version with anonymous function and recursion (just for the craic)!

var LOWERBOUND = 1;
var UPPERBOUND = 100;
var LINEBREAK = ‘
’;
var FIZZBUZZ = [
[3,‘Fizz’],
[5,‘Buzz’]
];

(function (num) {
if(num <= UPPERBOUND) {
var output = ‘’;
for(var i = 0, fixzzBuzzLen = FIZZBUZZ.length; i < fixzzBuzzLen; i++) {
if(num % FIZZBUZZ[i][0] == 0) {
output += FIZZBUZZ[i][1];
}
}
return document.write((output.length > 0 ? output : num) + LINEBREAK) + arguments.callee(++num);
}
return;
})(LOWERBOUND);


#137

For completeness - in Aubit4GL :

main
define a integer
for a=1 to 100
case
when a mod 5=0 and a mod 3=0
display a, " FizzBuzz"
when a mod 5=0
display a, " Buzz"
when a mod 3=0
display a, " Fizz"
otherwise
display a
end case
end for
end main


#138

Oh yeah - my contribution.

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

I’m a software engineer - and if I was hiring, I would check the “readability” and “understandability” of the solution. Tricky and cute code that is unmodifiable and decipherable might work - but how well will the developer work with others? And how likely is his/her code going to adapt to continually changing requirements.


#139

@Corey:

You just failed at either reading comprehension or at coding:

for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print "fizzbuzz"
elif i % 5 == 0:
print "buzz"
elif i % 3 == 0:
print "fizz"
else:
print i


#140

? “1”;
? “2”;
? “Fizz”;
? “4”;
? “Buzz”;
? “Fizz”;
? “7”;
? “8”;
? “Fizz”;
? “Buzz”;
? “11”;
? “Fizz”;
? “13”;
? “14”;
? “FizzBuzz”;
? “16”;