Election the king of monkey in PHP

Share with you !

Background : 

Amount of monkey N in a circle, identifiering from 1 to N. We choose a random number M to count these monkey, when reaching M, the Mth monkey will be kicked out, and continue, until there is only one luck monkey, he will be the king.

(Is this the algo of Joseph ?  To be verified !)

Program in PHP :

function election($total, $step) {
 $tmp = 0;
 
 for ($i = 2; $i <= $total; $i++) {
     $tmp = ($tmp + $step) % $i;
 }
 
 $winner = $tmp + 1;
 
 return $tmp;
}

If there are other methods to do it more efficient, merci de me dire !

Advertisements

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