0

假设我有五个变量 a、b、c、d 和 e,它们都被分配了一个来自五个不同范围的随机数,对应于五个变量 a 到 e。

有没有办法分配第六个变量 x,它从一个上限值等于 a+b+c+d+e 的总和的范围中选择一个随机数?

例如,说:-

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)

感谢您的帮助

4

4 回答 4

1

您可以使用

Min + (int)(Math.random() * ((Max - Min) + 1))

其中 Min = a 和 Max = a+b+c+d+e

于 2013-07-07T15:30:07.147 回答
1

From 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:

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(); however, Math.random() returns a double in range: [0,1). So, if you have min = 0, max = 9, and want a number between [0,9], then you need:

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))
于 2013-07-07T15:31:48.167 回答
0

像这样的东西应该可以完成这项工作

            Random generator = new Random();
            generator.setSeed(System.currentTimeMillis());
            long range = a+b+c+d+e;
            long fraction = (long)(range * generator.nextDouble());
            randomNumber =  (int)(fraction);  
于 2013-07-07T15:32:31.627 回答
0

Edit: I missunderstood your problem, but you just need to sum each var and do the same thing. 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)));
于 2013-07-07T15:32:00.230 回答