Home  >  Article  >  Daily Programming  >  PHP random selection algorithm (1)

PHP random selection algorithm (1)

藏色散人
藏色散人Original
2019-02-18 14:31:3911071browse

In our daily PHP interview process, algorithmic questions are naturally indispensable, and everyone knows that algorithms are the core of the program. So starting from this article, we will successively introduce to you the knowledge related to the PHP algorithm series. Below we will introduce to you the PHP random selection algorithm.

PHP random selection algorithm (1)

PHP algorithm, as the name suggests, uses PHP to find the only element that meets the requirements among multiple elements.

For example, there is a specific interview question about the PHP algorithm. The question is as follows:

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 the end. Until there is only one monkey left, that monkey is called the king.

Requires PHP programming to simulate this process, input m, n, and output the number of the last king.

The solution is as follows:

<?php
function king($n, $m){
    $monkeys = range(1, $n);
    $i=0;
    while (count($monkeys)>1) {
        if(($i+1)%$m==0) {
            unset($monkeys[$i]);
        } else {
            array_push($monkeys,$monkeys[$i]);
            unset($monkeys[$i]);
        }
        $i++;
    }
    return current($monkeys);
}
echo king(10,3);

Due to the length of the article, this section will be introduced here first. You can also actually understand the operation and solution methods locally first. In the follow-up article "PHP Random Picking One Algorithm (2)", we will combine the above code and continue to introduce the implementation process of PHP picking one algorithm in detail.

The above is the detailed content of PHP random selection algorithm (1). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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