Home > Backend Development > PHP Tutorial > Solution to the problem of PHP monkey choosing the king, Monkey King_PHP Tutorial

Solution to the problem of PHP monkey choosing the king, Monkey King_PHP Tutorial

WBOY
Release: 2016-07-13 09:54:14
Original
1353 people have browsed it

How to solve the problem of monkey choosing the king in php, monkey king

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:

<&#63;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));
&#63;>
Copy after login

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998550.htmlTechArticleHow to solve the problem of php monkey choosing the king, Monkey King This article tells the example of how to solve the problem of php monkey choosing the king. Share it with everyone for your reference. The specific analysis is as follows: Problem description:...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template