Take n random elements from a List?

后端 未结 12 1554
天涯浪人
天涯浪人 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:41

    This solution doesn't modify the original list or otherwise scale in complexity with the list size.

    To get a sample of 4 from a list of 7, we just select a random element out of all 7, then select a random element out of the remaining 6, and so on. If we've already selected indices 4, 0, 3, next we generate a random number out of 0, 1, 2, 3, respectively representing index 1, 2, 5, 6.

    static Random rand = new Random();
    
    static  List randomSample(List list, int size) {
        List sample = new ArrayList<>();
    
        for (int sortedSampleIndices[] = new int[size], i = 0; i < size; i++) {
            int index = rand.nextInt(list.size() - i);
    
            int j = 0;
            for (; j < i && index >= sortedSampleIndices[j]; j++)
                index++;
            sample.add(list.get(index));
    
            for (; j <= i; j++) {
                int temp = sortedSampleIndices[j];
                sortedSampleIndices[j] = index;
                index = temp;
            }
        }
    
        return sample;
    }
    

提交回复
热议问题