Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random numbers between two numbers

public class TestSample {
    public static void main(String[] args) { 

        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);

        double ran = Math.random();



    }
}

I don't want to use Random r = new Random(); class. Is there any other way to generate random numbers. I am just struck with what logic could be applied to generate random numbers between two numbers.

like image 901
John Cooper Avatar asked Dec 12 '22 09:12

John Cooper


2 Answers

It's really easy... you only need to figure out which is the minimum value and what is the difference between the two numbers (let's call it diff). Then, you can scale the Math.random value (between 0 and 1) by multiplying by diff (now its range is between 0 and diff). Then, if you add the minimum value, your range is between min and min + diff (which is the other value)

int min = min(a,b);
int max = max(a,b);

int diff = max - min;

int result = min + diff * Math.random();
like image 198
Matteo Avatar answered Jan 04 '23 09:01

Matteo


Consider using this code:

int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double ran = Math.random();
double random;

if(a < b)
    random = (b-a)*ran + a;
else
    random = (a-b)*ran + b;

This will work for a >= 0 and b >= 0 if you consider using negative number the logic sligtly changes

like image 34
Stefano Avatar answered Jan 04 '23 08:01

Stefano