PHP algorithm Monkey King game

Source: Internet
Author: User
Monkey King game

A group of monkeys are arranged in a circle. Numbers are arranged in sequence by 1, 2,... and N.

Then start counting from the first one, count to the m, and kick it out of the circle, and start counting from behind it.

Count to m and kick it out... so it keeps going.

Until there is only one monkey left, the monkey is called the King.

Programming to simulate this process, input M, N. output the number of the last king.
  1. Function monkeyking ($ N, $ m ){
  2. $ Monkeys = range (1, $ N );
  3. $ I = 0; // coordinates of the retrieved data
  4. $ Z = 0; // stop when you count to m
  5. While ($ mnum = count ($ monkeys)> 1 ){
  6. If ($ I = $ mnum ){
  7. $ I = 0; // circle
  8. }
  9. $ Z ++;
  10. $ I ++;
  11. If ($ z = $ m ){
  12. Array_splice ($ monkeys, -- $ I, 1 );
  13. $ Z = 0; // return to zero
  14. }
  15. }
  16. Return ($ monkeys [0]);
  17. }

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.