During the interview, a group of monkeys arranged in a circle and numbered 1, 2,... and n. Then start counting from 1st, count to m, kick it out of the circle, start counting from behind it, count to m, and kick it out ..., the monkey is called the King until there is only one monkey. Programming simulation required "> <LINKhref =" http://www.php100.c
During the interview, I encountered the following question:
A group of monkeys are arranged in a circle and numbered by 1, 2,... and n. Then start counting from 1st, count to m, kick it out of the circle, start counting from behind it, count to m, and kick it out ..., the monkey is called the King until there is only one monkey. Programming to simulate this process, input m, n, and output the number of the last king.
Joseph's algorithm, haha. I read the code of the prawns on the Internet, and it was not easy to understand and complicated, so I wrote a code segment myself.
/**
* Monkey election King
*
* @ Param int $ m number of monkeys
* @ Param int $ n number of outgoing calls
* @ Return array
*
*/
Function king ($ m, $ n)
{
// Construct an array
For ($ I = 1; $ I <$ m + 1; $ I ++ ){
$ Arr [] = $ I;
}
$ I = 0; // you can specify an array pointer.
While (count ($ arr)> 1)
{
// Traverses the array to determine whether the current Monkey is the sequence number. If so, the monkey is out. Otherwise, it is placed at the end of the array.
If ($ I + 1) % $ n = 0 ){
Unset ($ arr [$ I]);
} Else {
Array_push ($ arr, $ arr [$ I]); // This round of non-outbound monkeys are placed at the end of the array.
Unset ($ arr [$ I]); // delete
}
$ I ++;
}
Return $ arr;
}
Var_dump (king (6, 4 ));
King 5