Page 1 of 1

Facebook Challenge

Posted: Mon Apr 19, 2010 6:34 pm
by timWebUK
I decided to start doing the Facebook coding puzzles for a bit of practice and have managed to solve the first one pretty easily:

http://www.facebook.com/careers/puzzles ... uzzle_id=7

I was wondering if you could critique the efficiency of my code and perhaps suggest better methods of doing it? I just hate the look of the IF statements and feel I could be doing it a much better way.

Code: Select all

<?php
// Facebook Hoppity Hop! Challenge //

//Setup
	//Constants
	define('DIVTHREE',"Hoppity\n");
	define('DIVFIVE',"Hophop\n");
	define('DIVTHREEANDFIVE',"Hop\n");
	//Retrieve integer
	$theFile = $argv[1];
	$fileHandle = fopen($theFile, 'r');
	$strTxtValue = fread($fileHandle, filesize($theFile));
	fclose($fileHandle);
	$intTxtValue = (int)trim($strTxtValue);
	//Booleans
	$bThree = false;
	$bFive = false;
//Functions	
	//Check if divisible
	function checkDiv($intTxtValue)
	{
		for($i = 1; $i <= $intTxtValue; $i++)
		{	
			if(($i % 3) === 0)
			{
				$bThree = true;
			}
			if(($i % 5) === 0)
			{
				$bFive = true;
			}
			if($bThree && $bFive)
			{
				echo DIVTHREEANDFIVE;
			}
			elseif($bThree)
			{
				echo DIVTHREE;
			}
			elseif($bFive)
			{
				echo DIVFIVE;
			}
			
			//Reinitialize as false
			$bThree = false;
			$bFive = false;
		}
	}
//Main
	//Call checkDiv()	
		checkDiv($intTxtValue);	
?>
Cheers!

Re: Facebook Challenge

Posted: Tue Apr 20, 2010 4:11 am
by timWebUK
I realised myself I could easily cut short the opening and reading sequence and also lose the whole boolean flag idea if I just rearranged my if statements!

Code: Select all

<?php
// Facebook Hoppity Hop! Challenge //
$intTxtValue = (int)trim(file_get_contents($argv[1]));
for($i = 1; $i <= $intTxtValue; $i++)
{       
	if($i % 3 === 0 && $i % 5 === 0)
    {
		echo "Hop\n";
	}
	elseif($i % 3 === 0)
	{
		echo "Hoppity\n";
	}
	elseif($i % 5 === 0)
	{
		echo "Hophop\n";
	}
}
?>
Any other suggestions?