简体   繁体   English

在Java中生成以N的倍数递增的随机数

[英]Generate random numbers increasing by multiples of N in Java

I need to write a short randomizer which generates a random number between 1 to N where the random number is increasing by multiples of M. 我需要编写一个简短的随机数生成器,生成一个介于1到N之间的随机数,其中随机数以M的倍数递增。

For example: generate numbers between 1 and (N=30) increasing by multiples of (M=5). 例如:生成1到(N = 30)之间的数字,该数字以(M = 5)的倍数递增。 The only possible generated numbers can be then: 1,5,10,15,20,25 and 30. Hope you get what I mean :) 唯一可能生成的数字可以是:1,5,10,15,20,25和30。希望您明白我的意思:)

Normally if you use new Random().nextInt(30)+1 , you get numbers increasing by multiples of 1 (1,2,3,4,5,6,7,etc.). 通常,如果您使用new Random().nextInt(30)+1 ,则得到的数字new Random().nextInt(30)+1的倍数增加(1、2、3、4、5、6、7等)。 That is not what I want. 那不是我想要的。

Any help, links, or directions are very appreciated? 任何帮助,链接或指示都非常感谢?

EDIT : 编辑

That the sequence of generated random numbers could include 1 not zero is one of the requirements of the method. 该方法的要求之一是,所生成的随机数的序列可以包括1而不是零。 Precisely, the sequence always starts with the lower bound (min). 准确地说,序列始终以下限(min)开始。 In the example the lower bound is 1 and therefore there can't be zero in the sequence. 在示例中,下限为1,因此序列中不能为零。 It's odd I know, but those are the requirements I have to follow ;) 我知道这很奇怪,但是我必须遵循这些要求;)

You could multiply the random value by 5. Since you want to have 1 instead of 0 just look for that value and alter it specifically: 您可以将随机值乘以5。由于您希望使用1而不是0,因此只需查找该值并进行专门更改即可:

static final Random random = new Random(System.currentTimeMillis());

public int random(int range, int multiple) {
    int value = random.nextInt(range / multiple) * multiple;
    return value == 0 ? 1 : value;
}

I think that your example is a little bit flawed: the sequence should be (0, 5, 10, 15, 20, 25, 30) 我认为您的示例有些瑕疵:顺序应为(0,5,10,15,20,25,30)

If I'm correct, you can then use: 如果我是正确的,则可以使用:

new Random().nextInt(7) * 5; // will generate a number between 0 and 7 not included then multiply by 5 which should give what you want

If you want to start by 1, then just add it to the previous statement 如果要从1开始,则只需将其添加到上一个语句中

Try this.. 尝试这个..

public static void main(String[] args){
    int N = 50;
    int M = 5;
    System.out.println(getRandomNumber(N, M));

}

static int getRandomNumber(int n, int m){
    Random r = new Random();
    int rnd = r.nextInt(n);
    return rnd%m == 0?rnd:getRandomNumber(n, m);
}
int n=Random.range(1,10);
n=n*100;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM