Take n random elements from a List?

后端 未结 12 1551
天涯浪人
天涯浪人 2020-11-27 16:09

How can I take n random elements from an ArrayList? Ideally, I\'d like to be able to make successive calls to the take() method to get an

12条回答
  •  攒了一身酷
    2020-11-27 16:39

    A fair way to do this is to go through the list, on the nth iteration calculating the probability of whether or not to pick the nth element, which is essentially the fraction of the number of items you still need to pick over the number of elements available in the rest of the list. For example:

    public static  T[] pickSample(T[] population, int nSamplesNeeded, Random r) {
      T[] ret = (T[]) Array.newInstance(population.getClass().getComponentType(),
                                        nSamplesNeeded);
      int nPicked = 0, i = 0, nLeft = population.length;
      while (nSamplesNeeded > 0) {
        int rand = r.nextInt(nLeft);
        if (rand < nSamplesNeeded) {
          ret[nPicked++] = population[i];
          nSamplesNeeded--;
        }
        nLeft--;
        i++;
      }
      return ret;
    }
    

    (This code copied from a page I wrote a while ago on picking a random sample from a list.)

提交回复
热议问题