FizzBuzz and a false coin

I just had my co-worker visit me at home. We all work remotely so we don’t see each other on a daily basis, but he was passing through town. He brought up an interesting topic; a programming “test” called “FizzBuzz”.

The rules: Print out all values between 1 and 100. When a number is divisible by 3 print “FIZZ” and when divisible by 5 print “BUZZ”. When the number is divisible by both, print “FIZZ BUZZ”.

My simple solution to it (a Perl script) is as follows:

for ($i = 1; $i <= 100; $i++) {
 print "$i:\t";
 if ($i%3==0) { print "FIZZ "; }
 if ($i%5==0) { print "BUZZ "; }
 print "\n";

This meets the criteria, though I don’t check if a number is specifically divisible by both within a condition.

This brought back a memory of an “Algorithm Analysis” exam from University. I call it “The False Coin” problem, though it probably has many names.

You have a pile of coins. All of the coins are equal, except one, which is lighter than the other coins. This is the false coin. You also have a scale which allows you to compare two weights against each other. Using the scale, what is the most efficient way to find the false coin?

The other students insisted you split the pile of coins into two equal piles, weigh the two against each other and find the lighter pile, then split the lighter pile into two piles, and so on.

Close. But wrong. There is a better way and it involves splitting the first pile into three equal piles. Compare two piles, identify which of the three is the lightest pile and split that into three more equal piles, and so on. With every weighing you get rid of 66% of the remaining coins, compared to only 50% when splitting the piles by half.

So keep that in mind before your next programming interview.

Leave a Reply


Staypressed theme by Themocracy