简体   繁体   中英

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.

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?

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

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))

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)));

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);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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