Choosing k out of n

前端 未结 3 466
心在旅途
心在旅途 2021-02-04 01:45

I want to choose k elements uniformly at random out of a possible n without choosing the same number twice. There are two trivial approaches to this.

3条回答
  •  故里飘歌
    2021-02-04 02:37

    What you could use is the following algorithm (using javascript instead of pseudocode):

    var k = 3;
    var n = [1,2,3,4,5,6];
    
    // O(k) iterations
    for(var i = 0, tmp; i < k; ++i) {
    
        // Random index O(1)
        var index = Math.floor(Math.random() * (n.length - i));
    
        // Output O(1)
        console.log(n[index]);
    
        // Swap and lookup O(1)
        tmp = n[index];
        n[index] = n[n.length - i - 1];
        n[n.length - i - 1] = tmp;
    }
    

    In short, you swap the selected value with the last item and in the next iteration sample from the reduced subset. This assumes your original set is wholly unique.

    The storage is O(n), if you wish to retrieve the numbers as a set, just refer to the last k entries from n.

提交回复
热议问题