从列表中随机选择的选项多于列出的项目

时间:2016-09-27 00:03:06

标签: groovy

我是Groovy的新手,所以如果这是一个菜鸟问题我会道歉。

我有一个50长的项目列表,它们都是由1-50的ID号识别的。我希望能够从列表中随机选择多次,而不是列表中的项目(现在122,但可能比这多出几倍)。我试过的当前代码是:

list.shuffle.next(122).each {}

我遇到的问题是括号内创建的操作只会迭代次数,因为我在列表中有数字(50)。而不是50次,然后50次,然后22次(其中每个项目将被选择至少两次,不超过3次),我宁愿选择真正随机的方法。

有什么更好的方式来写这个?

谢谢!

2 个答案:

答案 0 :(得分:4)

Here's a groovy way to do it.

// list of integers 1 to 50
def list = 1..50

// where you're going to store your picks from
def selection = []

// what you're going to pick
def random = new Random()

// 0 to 121 is 122 items
(0..121).each {
    // pick from the list at random
    selection << list[ random.nextInt(list.size()) ]
}

答案 1 :(得分:1)

您可以使用java.util.Random选择列表中的随机元素:

List<Object> list = new ArrayList<>(); //fill this list with objects
List<Object> results = new ArrayList<>(); //results will be saved in here
Random rng = new Random(); //a new random number generator
int i = 0;
while (i++ < 100) {
  int randomIndex = rng.nextInt(list.size()); //random index in the list
  Object result = list.get(randomIndex);
  results.add(result);
}

最后,results中会有100个结果,从list中随机挑选。

在旁注中,此代码显然不适用于空列表并抛出IndexOutOfBoundsException