[英]Random number from a series of random numbers in Java?
Say i have five variables a,b,c,d and e which are all assigned a random number from five different ranges corresponding to to the five variables a to e. 假设我有五个变量a,b,c,d和e,它们都分配了对应于五个变量a到e的五个不同范围的随机数。
Is there a way to assign a sixth variable say x, that chooses a random number from a range with upper value equal to the total of a+b+c+d+e? 有没有办法分配第六个变量说x,从一个上限值等于a + b + c + d + e的总和的范围中选择一个随机数?
for example, say :- 例如,说: -
a=5 (range 0-10)
b=1043 (range 0-2000)
c=37 (range 0-38)
d=2 (range 0-100)
e=20 (range 5-30)
then x = (random number) (range 5- 1107)
Thanks for any assistance 谢谢你的帮助
You can use 您可以使用
Min + (int)(Math.random() * ((Max - Min) + 1))
Where Min = a and Max = a+b+c+d+e 其中Min = a且Max = a + b + c + d + e
From java.util.Random
: 来自
java.util.Random
:
Random rand = new Random();
rand.nextInt(X);
//returns an `int` in range: [0,X)
So, if you have a
, b
, ..., n
, to get a number in between 0 and the sum of the variables, we do: 所以,如果你有
a
, b
,..., n
来得到介于0和变量之和的数字,我们可以:
rand.nextInt(a + b + ... + n + 1); //returns an `int` in range [0, sum(a,b,...,n)]
As other users have suggested, you can also use Math.random()
; 正如其他用户所建议的那样,你也可以使用
Math.random()
; however, Math.random()
returns a double
in range: [0,1)
. 但是,
Math.random()
返回范围内的double
精度: [0,1)
。 So, if you have min = 0
, max = 9
, and want a number between [0,9]
, then you need: 所以,如果你有
min = 0
, max = 9
,并且想要一个介于[0,9]
之间的数字,那么你需要:
Min + (int)(Math.round((Math.random() * (Max - Min))))
//need to cast to int since Math.round(double returns a long)
or you could do:
Min + (int)(Math.random() * (Max - Min + 1))
Edit: I missunderstood your problem, but you just need to sum each var and do the same thing. 编辑:我很想念你的问题,但你只需要对每个var求和并做同样的事情。 Some answers already showed that.
一些答案已经显示出来了。
It is just a algorithm problem. 这只是一个算法问题。
int lra = 0; // lower range of a
int ura = 10; // upper range of a
int lrb = 0;
int urb = 2000;
// a couple of ranges for each var...
int a = lra + ((int) (Math.random() * (ura - lra)));
// the same for each var...
int lrs = lra + lrb + ...; // sum of lower ranges...
int urs = ura + urb + ...; // sum of upper ranges
int x = lrs + ((int) (Math.random() * (urs - lrs)));
Something like this should do the job 像这样的东西应该做的工作
Random generator = new Random();
generator.setSeed(System.currentTimeMillis());
long range = a+b+c+d+e;
long fraction = (long)(range * generator.nextDouble());
randomNumber = (int)(fraction);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.