[PHP] Monkey King

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.