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.