Fizz Buzz: What is all the fuss about?
October 31, 2017
In past interviews I have been asked to answer some technical questions and also solve some code challenges.
They often vary in complexity and also give a good insight in to the calibre of developer/company that you are interviewing for.
One that has always amused me is the classic Fizz Buzz test. They often vary in requirements just enough so that you can’t always use a generic solution.
Development Task
Business requirements
- Write a class with a method that takes 2 integers between 1 and 100.
- Loop over the integers.
- Write out each integer.
- If the integer is divisible by 3 also print out “fizz”
- If the integer is divisible by 5 also print out “buzz”
Development requirements
Before you write any other code write some unit tests
Solution
I have created a solution that can be found here. I would love to know thoughts on this solution or a better solution (you can make a comment on the github repo if you like).
If you don’t want to follow the link, the example is below:
<?php
namespace FizzBuzz;
class Processor
{
/**
* This method takes two arguments $from and $to then creates a for loop
* within is the logic of whether to print:
* - 'Fizz'
* - 'Buzz'
* - 'FizzBuzz'
*
* @param int $from
* @param int $to
* @throws \InvalidArgumentException
*/
public function process(int $from, int $to)
{
if ($from < 1) {
throw new \InvalidArgumentException(
'From must be greater than or equal to 1'
);
}
if ($to > 100) {
throw new \InvalidArgumentException(
'To must be less than or equal to 100'
);
}
if ($to <= $from) {
throw new \InvalidArgumentException(
'To must be greater than From'
);
}
for ($i = $from; $i <= $to; $i++) {
// Print out the number
print $i;
if ($this->numberSatisfiesConstraint($i, 15)) {
// If a number is divisible by 5 and 3 it can only be divisible
// by 15 with no remainder
// therefore print `fizzbuzz`
print 'fizzbuzz';
} elseif ($this->numberSatisfiesConstraint($i, 3)) {
// If a number is divisible by 3 with no remainder print `fizz`
print 'fizz';
} elseif ($this->numberSatisfiesConstraint($i, 5)) {
// If a number is divisible by 5 with no remainder print `buzz`
print 'buzz';
}
// Print out a new line
print PHP_EOL;
}
}
/**
* Check that the passed number satisfies the given constraint and has no
* remainders
*
* @param int $number
* @param int $constraint
* @return bool
*/
protected function numberSatisfiesConstraint(int $number, int $constraint)
{
return $number % $constraint == 0;
}
}
This can be used like:
<?php
require_once 'vendor/autoload.php';
$fizzBuzzProcessor = new \FizzBuzz\Processor();
$fizzBuzzProcessor->process(1, 100);
?>