Facebook Challenge

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Facebook Challenge

Post 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!
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Re: Facebook Challenge

Post 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?
Post Reply