没有重复值的循环

Loop with no duplicate values

问题描述。

  1. 选择一个介于 0 和 4 之间的数字(随机数字将指示将显示列表中的多少个值)
  2. 从列表中获取随机值,使其唯一并显示为结果。

我的代码不起作用,请告诉我如何修复它。我会很感激你的帮助。

import groovy.json.JsonOutput
import java.util.Random 
Random random = new Random()
def num = ["0","1","2","3","4"]
def randomNum = random.nextInt(num.size())
def  min = 0;
def  max = num[randomNum];
def list = ["Toy", "Mouse", "Cup","Book","Tiger"]
while(max > min) { 
   def randomValue = random.nextInt(list.size())
   def theValue = list[randomValue] + '"'+ "," +
   max++;
}

我想达到的结果例如是: Toy","Cup(如果随机抽取2) Toy","Tiger","Book"(若随机抽取3个)

the available number is from 0 to 4 as many as there are possible elements to choose from 0 - Toy, 1 - Mouse 2- Cup 3- Book 4 - tiger. First, a number, e.g. 2, is drawn and then 2 elements are selected randomly from the list of values.

你可以这样做:

Random random = new Random()

def list = ["Toy", "Mouse", "Cup","Book","Tiger"]

// this allows zero to be selected... if that is a violation
// of the requirement, adjust this....
int numberOfElementsToSelect = random.nextInt(list.size())

def results = []
numberOfElementsToSelect.times {
    results << list.remove(random.nextInt(list.size()))
}
println results
println results.join(',')

编辑:

Works great, I have one more question what to do to exit the script without showing any results in case the value is empty

如果您想在不显示结果的情况下退出脚本,您可以这样做:

Random random = new Random()

def list = ["Toy", "Mouse", "Cup","Book","Tiger"]

// this allows zero to be selected... if that is a violation
// of the requirement, adjust this....
int numberOfElementsToSelect = random.nextInt(list.size())

def results = []
numberOfElementsToSelect.times {
    results << list.remove(random.nextInt(list.size()))
}
if(results) {
   // do what you want with the results, like...
   println results.join(',')
} else {
   // do something else, could be exit the script...
   System.exit(-2)
}