Skip to content

Instantly share code, notes, and snippets.

@toddnestor
Created January 24, 2014 20:16
Show Gist options
  • Save toddnestor/8605407 to your computer and use it in GitHub Desktop.
Save toddnestor/8605407 to your computer and use it in GitHub Desktop.
The FizzBuzz problem
<?php
//I already posted this in response to another post, but I wanted to get it to where you all could see it
//classes which would typically be kept in separate files named htmlCode.class.php and numberFunctions.class.php respectively
class htmlCode
{
public function __construct()
{
}
public function br($echo=0, $qty=1)
{
$string = '';
for($int=1;$int<=$qty;$int++) $string .= '<br />';
echo $echo ? $string:'';
return $string;
}
}
class numberFunctions
{
public function __construct()
{
$this->html = new htmlCode();
}
public function factorize($int)
{
$factors = array();
for($i=1;$i<=sqrt($int);$i++)
{
if($int % $i)
{
}
else
{
$factors[] = $i;
if($i != sqrt($int)) $factors[] = $int/$i;
}
}
sort($factors);
return $factors;
}
public function replaceFactorsWithWords($int,$cases = array())
{
$printMe = '';
$factors = $this->factorize($int);
foreach($factors as $factor)
{
$printMe .= isset($cases[$factor]) ? $cases[$factor]:'';
}
return $printMe;
}
public function replaceNumbersDivisible($cases=array(),$min=1,$max=100,$breaksInBetween=1)
{
$string = '';
for($i=$min;$i<=$max;$i++)
{
$result = $this->replaceFactorsWithWords($i,$cases);
$result = $result != '' ? $result:$i;
$result .= $this->html->br(0,$breaksInBetween);
$string .= $result;
}
return $string;
}
}
//class definitions
$numbers = new numberFunctions();
//defining the cases in which to print things
$cases = array(3=>'Fizz',5=>'Buzz');
echo $numbers->replaceNumbersDivisible($cases);
?>
<?php for ( $i=1; $i <= 100; $i++ ) echo ($i % 15 ? ($i % 5 ? ($i % 3 ? $i:'Fizz'):'Buzz') : 'FizzBuzz').'<br />';?>
@toddnestor
Copy link
Author

The first code above is my response to the common FizzBuzz problem, which states:

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".

So I wrote the program like I normally would which is in a way so as to maximize reusability and flexibility. If you changed some variables it could start at any number and end at any number, change the amount of lines between numbers, use different words or even add words for different variables like print 'Cool, Inc.' for multiples of 7.

if you simply wanted to get it to work without going through all this trouble you could simply write the second code I provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment