Efficiently pick n random elements from PHP array (without shuffle)

前端 未结 5 2025
独厮守ぢ
独厮守ぢ 2020-11-29 12:05

I have the following code to pick $n elements from an array $array in PHP:

shuffle($array);
$result = array_splice($array, 0, $n);
         


        
5条回答
  •  迷失自我
    2020-11-29 12:41

    This will only show benifits for small n compared to an array shuffle, but you could

    1. Choose a random index r n times, each time decreasing the limit by 1
    2. Adjust for previously used indices
    3. Take value
    4. Store used index

    Pseudocode

    arr = []
    used = []
    for i = 0..n-1:
        r = rand 0..len-i
        d = 0
        for j = 0..used.length-1:
            if r >= used[j]:
                d += 1
        arr.append($array[r + d])
        used.append(r)
    return arr
    

提交回复
热议问题