This article describes the solution to the problem of monkey choosing the king in php. Share it with everyone for your reference. The specific analysis is as follows:
Problem description:
A group of monkeys line up in a circle and are numbered according to 1, 2,..., n. Then start counting from the 1st one, count to the mth one, kick it out of the circle, start counting from behind it, count to the mth one, kick it out..., and continue in this way, Until there is only one monkey left, that monkey is called the king. Programming is required to simulate this process, enter m, n,
Output the number of the last king.
Solution:
<?php function king($m, $n) { for($i = 1;$i < $m + 1;$i++) { //构建数组 $arr[] = $i; } $i = 0;//设置数组指针 while (count($arr) > 1) { //遍历数组,判断当前猴子是否为出局序号, //如果是则出局,否则放到数组最后 if (($i + 1) % $n == 0) { unset($arr[$i]); } else { array_push($arr, $arr[$i]); //本轮非出局猴子放数组尾部 unset($arr[$i]); //删除 } $i++; } return $arr; } var_dump(king(100,5)); ?>
I hope this article will be helpful to everyone’s PHP programming design.