Jiangyue Zhu

Impossible is Nothing

Survivor Game–PHP Programming

Leave a comment

I did a PHP program as a coding test for one technical interview. The test was to use PHP to implement a function to play the ‘Survivor’ game. The game rule is like this:

You are in a room with a circle of 100 chairs.  The chairs are numbered sequentially from 1 to 100.At some point in time, the person in chair #1 will be asked to leave.  The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left… the survivor.

 

So what the function needs to do is to find out the survivor (which chair the survivor is sitting in).

My codes are like this:

<?php
/* Function remove consists of two args. One is the integer array, the other is
 * the token to control removal: 1--remove 0--not remove
 *
 * When there is only one element left in the array, then the survivor found
 */
function survivor($array,$rmToken){

 /**
 * if only one left, return it. The survivor found!**/
 if(count($array) == 1){

 return $array;
 }
foreach($array as $key => $element){
 /**
 * token equals to 1
 * Remove current element from array
 * set token to 0, continue loop
 */
 if($rmToken){ 

 unset($array[$key]); 

 $rmToken = 0; 

 }

 /**
 * token equals to 0
 * skip this element
 * set token to 1, continue loop **/
 else { 

 $rmToken = 1; 

 }

 }// end foreach

 return survivor($array,$rmToken); //recursive 

}

// create an array containing a range of elements, from 1 to 100.
 $arr = range(1,100);
$result = survivor($arr,1); //call survivor function, return result
echo "The survivor is sitting on #".array_pop($result);
 // print_r($result);
?>
Advertisements

Author: zhujy8833

Impossible is nothing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s