Choosing k out of n

前端 未结 3 452
心在旅途
心在旅途 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:31

    With an O(1) hash table, the partial Fisher-Yates method can be made to run in O(k) time and space. The trick is simply to store only the changed elements of the array in the hash table.

    Here's a simple example in Java:

    public static int[] getRandomSelection (int k, int n, Random rng) {
        if (k > n) throw new IllegalArgumentException(
            "Cannot choose " + k + " elements out of " + n + "."
        );
    
        HashMap hash = new HashMap(2*k);
        int[] output = new int[k];
    
        for (int i = 0; i < k; i++) {
            int j = i + rng.nextInt(n - i);
            output[i] = (hash.containsKey(j) ? hash.remove(j) : j);
            if (j > i) hash.put(j, (hash.containsKey(i) ? hash.remove(i) : i));
        }
        return output;
    }
    

    This code allocates a HashMap of 2×k buckets to store the modified elements (which should be enough to ensure that the hash table is never rehashed), and just runs a partial Fisher-Yates shuffle on it.

    Here's a quick test on Ideone; it picks two elements out of three 30,000 times, and counts the number of times each pair of elements gets chosen. For an unbiased shuffle, each ordered pair should appear approximately 5,000 (±100 or so) times, except for the impossible cases where both elements would be equal.

提交回复
热议问题