Generate array of random unique numbers in PHP

前端 未结 7 891
再見小時候
再見小時候 2020-12-11 15:09

I\'m trying to generate an array of random numbers from 0-n then shuffle (but ensure that the keys and values DO NOT match).

For example:

0 => 3
1         


        
7条回答
  •  失恋的感觉
    2020-12-11 15:37

    Here's a rather long, but also pretty efficient solution, I believe. Contrary to other solutions posted here, this cannot deadlock (unless $size<2), and this will not do a full shuffle every time one value doesn't fit. Instead, it will only replace that value with another, random value.

    function unique_list($size=5) {
    
        function all_unique($numbers) {
            foreach ($numbers as $key=>$value)
                if ($key==$value) return false;
            return true;
        }
        function flip($a, $b, &$numbers) {
            $numbers[$a] = $numbers[$a] + $numbers[$b];
            $numbers[$b] = $numbers[$a] - $numbers[$b];
            $numbers[$a] = $numbers[$a] - $numbers[$b];
        }
    
        $flip_count = 0;
        $numbers = range(0,$size-1);
        shuffle($numbers);
    
        while (!all_unique($numbers)) {
            foreach ($numbers as $key=>$value) {
                if ($key==$value) {
                    flip($key, rand(0,$size-1), $numbers);
                    $flip_count++;
                    break;
                }
            }
        }
    
        printf("Flipped %d values\n", $flip_count);
        return $numbers;
    
    }
    
    $list = unique_list(10);
    print_r($list);
    

    The above will print something similar to

    Flipped 1 value(s)
    Array
    (
        [0] => 2
        [1] => 5
        [2] => 7
        [3] => 9
        [4] => 6
        [5] => 3
        [6] => 1
        [7] => 8
        [8] => 0
        [9] => 4
    )
    

提交回复
热议问题