Home  >  Article  >  Backend Development  >  Randomly remove several different numbers from an array

Randomly remove several different numbers from an array

WBOY
WBOYOriginal
2016-08-08 09:21:451109browse
/*
 * 此程序是从一个不重复的数组中随机的取出若干个不同的元素
 * 难点是防止在取数的时候出现已经取到过的情况(特别是取到最后),需要尽可能的降低碰撞
 */
//第一种算法,CSDN上别人的想法
/*
$num = 0;
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
$arr = array();
$g = 5;
$tag = true;
while ($tag) {
    $count = count($array);
    $t = rand(0, 1);
    if ($t == 1) {
        $arr[] = $array[$num];
        unset($array[$num]);
    }
    $num ++;
    if (count($arr) == $g) {
        $tag = false;
    }
    if ($num == $count) {
        $num = 0;   //循环
    }
}


var_dump($arr);
*/
//第二种算法,自己想的。
//可以在每次取出数据之后将该数据和最后没有获取的数据替换,然后再去没有取得的数据中随机获取值


function swap(&$a, &$b)
{
    $temp = $b;
    $b = $a;
    $a = $temp;
}


$result = array();
$src = array();
for($i = 0 ; $i < 40 ; $i++)
{
    $src[] = $i + 1;
}
$arr_len = count($src);
$count = 20;
$index = 0;
while($index < $count)
{
    $random = rand(0, $arr_len - $index - 1);
    $result[] = $src[$random];
    swap($src[$random] , $src[$arr_len - $index - 1]);
    $index += 1;
}


print_r(json_encode($result));
print_r(json_encode($src));

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces how to randomly extract several different numbers from an array, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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