Most efficient way of randomly choosing a set of distinct integers

后端 未结 8 716
囚心锁ツ
囚心锁ツ 2020-12-01 07:04

I\'m looking for the most efficient algorithm to randomly choose a set of n distinct integers, where all the integers are in some range [0..maxValue].

Constraints:<

8条回答
  •  -上瘾入骨i
    2020-12-01 07:39

    Here is an optimal algorithm, assuming that we are allowed to use hashmaps. It runs in O(n) time and space (and not O(maxValue) time, which is too expensive).

    It is based on Floyd's random sample algorithm. See my blog post about it for details. The code is in Java:

    private static Random rnd = new Random();
    
    public static Set randomSample(int max, int n) {
        HashSet res = new HashSet(n);
        int count = max + 1;
        for (int i = count - n; i < count; i++) {
            Integer item = rnd.nextInt(i + 1);
            if (res.contains(item))
                res.add(i);
            else
                res.add(item);
        }
        return res;
    }
    

提交回复
热议问题