0

I am new to this group and this is my first post.

Can some one please help me to generate 5 Unique numbers in min and max range and then sort them in ascending order using groovy. note: I am doing this in soapui.

import org.apache.commons.lang.RandomStringUtils
import java.util.Random

Random r = new Random();
def i

List random_num

for (i=1;i<=5;i++)
{
    random_num(i) = r.nextInt(9+2)
    if(i>0)
    {
        if(random_num[i]==random_num[i-1])
        random_num[i] = r.nextInt(9+2)
    }
}

    random_num.sort() ;
    log.info random_num

thank you

2 Answers2

0

Your code is very Java-ish. Groovy was developed, partly to eliminate a lot of the Java ceremony.

This is what I use to generate a random number:

def randNum(minSize, maxSize) {
    return Math.abs(new Random().nextInt(maxSize + 1 - minSize) + minSize)
}

You can call that five times, collect the results in a list, and sort the list. To call a routine, you can use:

5.times {randNum(minSize, maxSize)}
ou_ryperd
  • 2,037
  • 2
  • 18
  • 23
  • Hi, thank you for the info. I need to get the unique numbers, will this return duplicate values if i run for 5 times? As i am new to the groovy, i am trying to declare the list, but some how i am failed. the code that i am using from your message is as below: def randNum(minSize, maxSize) { return Math.abs(new Random().nextInt(maxSize + 1 - minSize) + minSize) } def list = [5] list = 5.times {randNum(1, 55)} log.info list could you pls help me how to get the values to the list – Sudeeksha Honey Jul 08 '20 at 18:06
  • Hi, some how i succeeded to add the numbers to the list using below: def randNum(minSize, maxSize) { return Math.abs(new Random().nextInt(maxSize + 1 - minSize) + minSize) } def list = [] for (i=1;i<=5;i++) { list.add(randNum(1, 55)) } log.info list list.sort() log.info list but pls help me on the duplications check – Sudeeksha Honey Jul 08 '20 at 18:16
  • @SudeekshaHoney just check if a value is already in the list before adding it – ou_ryperd Jul 09 '20 at 17:08
  • Hi @ou_ryperd, yes, this is generating the unique numbers.... thank you – Sudeeksha Honey Jul 11 '20 at 17:02
0

The part about rand between a min and max can be found here.

For the other constraints:

  • Unique values: use a Set for your result
  • Ascending order: use a sorted Set

E.g.:

import java.util.concurrent.ThreadLocalRandom

def n = 5
def min = 5
def max = 42

def result = new TreeSet()

while (result.size()<n) {
    result << ThreadLocalRandom.current().nextInt(min, max + 1)
}

println result
// → [7, 8, 29, 37, 42]

Note: make sure max - min > n

cfrick
  • 35,203
  • 6
  • 56
  • 68