'Loop with no duplicate values

Description of the problem.

  1. Choose a number between 0 and 4 (the randomly number will indicate how many values from the list will be displayed)
  2. Get random values from list, so that they are unique and display as a result.

My code does not work, please let me know how to fix it. I will be grateful for your help.

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++;
}

The result that I would like to achieve is for example: Toy","Cup (if 2 is randomly selected) Toy","Tiger","Book" (if 3 is randomly selected)



Solution 1:[1]

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.

You could do something like this:

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(',')

EDIT:

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

If you want to exit the script without showing results, you could do something like this:

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)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1