How to solve the php monkey election problem, Monkey King

Source: Internet
Author: User

How to solve the php monkey election problem, Monkey King

This article describes how to solve the php monkey dawang problem. Share it with you for your reference. The specific analysis is as follows:

Problem description:

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. Require programming to simulate this process, input m, n,
Output the number of the last king.

Solution:

<? Phpfunction king ($ m, $ n) {for ($ I = 1; $ I <$ m + 1; $ I ++) {// construct an array $ arr [] = $ I ;}$ I = 0; // set the array pointer while (count ($ arr)> 1) {// traverse the array, determine whether the current monkey is the number of out, // if yes, It is out; otherwise, put it to the end of the array if ($ I + 1) % $ n = 0) {unset ($ arr [$ I]);} else {array_push ($ arr, $ arr [$ I]); // unset ($ arr [$ I]) at the end of the array for this round of non-outbound monkeys; // Delete} $ I ++;} return $ arr ;} var_dump (king ();?>

I hope this article will help you with php programming.

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.