How to solve the problem of PHP monkey selection

Source: Internet
Author: User

This article is an example of the selection of the King of PHP Monkey solution. Share to everyone for your reference. The specific analysis is as follows:

Problem Description:

A group of monkeys in a circle, press 1,2,...,n sequentially numbered. And then starting from the 1th number, count to M only, kick It out of the loop, start from behind it, Count to M only, kick It out ..., keep going until the last monkey is left, the monkey is called King. Requires programming to simulate this process, input m, N,

Output the number of the last king.

Workaround:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23-24 <?php function King ($m, $n) {for ($i = 1; $i < $m + 1; $i + +) {//build array $arr [] = $i;} $i = 0;//set array pointer while ($arr > 1) {//traversal array, to determine whether the current monkey is out of sequence,//If it is out, otherwise put the last if (($i + 1)% $n = = 0) {unset ($arr [$i]);} else {Array_push ($arr, $ arr[$i]); This round of non-knockout monkeys put array tail unset ($arr [$i]); Delete} $i + +; return $arr; Var_dump (King (100,5));?>

I hope this article will help you with your PHP program design.

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.