Most efficient way of randomly choosing a set of distinct integers

后端 未结 8 715
囚心锁ツ
囚心锁ツ 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条回答
  •  离开以前
    2020-12-01 07:44

    The trick is to use a variation of shuffle or in other words a partial shuffle.

    function random_pick( a, n ) 
    {
      N = len(a);
      n = min(n, N);
      picked = array_fill(0, n, 0); backup = array_fill(0, n, 0);
      // partially shuffle the array, and generate unbiased selection simultaneously
      // this is a variation on fisher-yates-knuth shuffle
      for (i=0; i=0; i--) // O(n) times
      { 
        selected = backup[ i ];
        value = a[ N ];
        a[ N ] = a[ selected ];
        a[ selected ] = value;
        N++;
      }
      return picked;
    }
    

    NOTE the algorithm is strictly O(n) in both time and space, produces unbiased selections (it is a partial unbiased shuffling) and does not need hasmaps (which may not be available and/or usualy hide a complexity behind their implementation, e.g fetch time is not O(1), it might even be O(n) in worst case)

    adapted from here

提交回复
热议问题