how can i use random numbers in groovy?

前端 未结 5 1015
野性不改
野性不改 2020-12-13 17:49

I use this method:

def getRandomNumber(int num){
    Random random = new Random()
    return random.getRandomDigits(num)
}

when I call it I

5条回答
  •  庸人自扰
    2020-12-13 18:37

    Generate pseudo random numbers between 1 and an [UPPER_LIMIT]

    You can use the following to generate a number between 1 and an upper limit.

    Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1

    Here is a specific example:

    Example - Generate pseudo random numbers in the range 1 to 600:

    Math.abs(new Random().nextInt() % 600) + 1
    

    This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.


    Generate pseudo random numbers between a [LOWER_LIMIT] and an [UPPER_LIMIT]

    If you want to use a lower bound that is not equal to 1 then you can use the following formula.

    Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]

    Here is a specific example:

    Example - Generate pseudo random numbers in the range of 40 to 99:

    Math.abs( new Random().nextInt() % (99 - 40) ) + 40
    

    This will generate a random number within a range of 40 and 99.

提交回复
热议问题