2
\$\begingroup\$

Most implementations of FizzBuzz that I've seen rely on 3 modulus operations. Mine does two and a Boolean. (Not implying one is better, just different)

I understand that FizzBuzz is supposedly not to identify great coders, but rather to weed out those that would fail, but I'd like to know if this solution would likely be viewed in positive terms by a potential employer.

<?php
function fizzbuzz($fizz,$buzz,$max=100){
    $output=array();

    for ($i=1; $i <= $max; $i++){
        $output[$i]=''; //If I ignore warnings, this isn't needed.
        if(!($i % $fizz)){
        $output[$i]="Fizz";    
        }
        if(!($i % $buzz)){
        $output[$i].="Buzz";    
        }
        if(!$output[$i]){
            $output[$i]=$i;
        }
    }
    return $output;
}

foreach(fizzbuzz(3,5) as $out){
    echo $out . "\n"; //or echo $out.'<br>';
}

See it work: Fizzbuzz

\$\endgroup\$
1
\$\begingroup\$

Some things I would look for on an interview question such as this:

  • Is the coder handling bad input cases? This is something you are not really doing now. What if non-integer values are passed for parameters? What if values are not > 0? Oftentimes in interview scenarios like this, I at least want to see the coder acknowledge (even if with a "todo" kind of comment) that validations need to take place. If I was the one writing this code in the interview, I would probably ask the interviewer if they want you to write the validation code or just get to the heart of the algorithm. Regardless of their answer, at least they understand that you acknowledge these edge cases. If you are doing this as an off-line coding test for an interview than I would for sure add in the validation so they don't think you missed this.
  • I would personally like to see more exact and meaningful comparisons rather than just vaguely truthy/falsey comparison.

Example:

// instead of
if(!($i % $fizz)){    
// something like this
if($i % $fizz === 0){

// instead of
if(!$output[$i]){   
// do this
if(empty($output[$i])) {

To me, the suggested replacement examples are more clear in intent. Also, I would be worried about developers that make a habit of loose or unclear comparisons as this could be indicative of someone who is writing error-prone code.

  • The comment //If I ignore warnings, this isn't needed. is really bothersome. Why would you ignore warnings? I think your initialization of this array key to an empty string makes sense, specifically in light of you wanting to check it after the moduli checks to see if it is still an empty string. Don't apologize for writing code that behaves properly.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.