0

Someone at work as poised the challenge to create a script that prints the FizzBuzz game in as few likes as possible using PHP

The challenge

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

My attempt:

foreach(range(1,100) as $i) {
  $val = ($i % 3 == 0 ? "Fizz" : "").($i % 5 == 0 ? "Buzz" : "");
  echo (empty($val) ? $i : $val) .  '<br />';
}

Someone's Pythons attempt

[ ("Fizz" if not i % 3 else "") + ("Buzz" if not i % 5 else "") + ("Baz" if not i % 7 else "") if _ else "" for i in range(0, 100) ]

Can you see how to make this better/improve it? Or even do it better?

Thanks for your time

Pez Cuckow
  • 14,048
  • 16
  • 80
  • 130

3 Answers3

20

The most optimized version:

echo "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n";
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
5

One size optimizations:

$val = ($i % 3 ? "" : "Fizz").($i % 5 ? "" : "Buzz");
              ^--- remove == 0       ^--- remove  == 0

PHP will handily convert the result of the modulo to a boolean for you, without the equality test.

And similarly

echo (!$val ? $i : $val);

No need for the empty() test - empty strings evaluate as a boolean false anyways.

And if you're on PHP 5.3+, you can use the shortcut ternary as well:

echo ($val ?: $i)
Marc B
  • 356,200
  • 43
  • 426
  • 500
2

foreach(range(1,100)as$i)echo(''==($x=($i%3==0?"Fizz":"").($i%5==0?"Buzz":""))?$i:$x).'<br />';

LeonardChallis
  • 7,759
  • 6
  • 45
  • 76