How to specify ranges to java.util.Random? [duplicate] - java

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I don't know why Java's designers didn't design java.util.Random objects to return random numbers like this:
rand.nextInt(minValue, maxValue);
I don't understand how to pass min and max values to this function. I've seen this recommended:
random.nextInt(max + 1 - (min)) + min
but what does that mean? Does that mean:
random.nextInt(FULL_RANGE + 1) + START_OF_RANGE
For example, if I wanted to generate values between -1 and 1, inclusive, is this how I do it:
int oneOfThreeChoices = rand.nextInt(1 + 1 + 1) - 1;

The API provides sufficient tools for you to complete this task. If you want an random int on the range [a,b], inclusive on both ends, use
int n = random.nextInt(b-a+1) + a
assuming that random is an object previously declared to be of type java.util.Random.

random.nextInt(bound) returns random number from 0 to bound (exclusive). For example random.nextInt(10) returns random number from 0 to 9.
So, if you want to return number from 5 to 15 (inclusive) just say
random.nextInt(11) + 5
Why java designers have not included more convenient API to JDK? I think because the way explained here is pretty simple and obvious.

Related

new Random().nextInt(999999) sometimes generates 5 digit number [duplicate]

This question already has answers here:
Java Generate Random Number Between Two Given Values [duplicate]
(7 answers)
Closed 5 years ago.
I am using new Random().nextInt(999999) to generate a 6 digit random number. But sometimes it generates 5 digit numbers. And I explicitly have to check if generated number is not 6 digit.
Why this method does that? And is there any other way to be pretty sure it generate only 6 digit random number.
Random().nextInt(999999) generates number between 0 and 999998, so you have ~10% chance to get number smaller than 100000 (5 and less digits).
Try
100000 + Random().nextInt(900000)
you will get number in range 100000 - 999999
Random().nextInt(999999) generates 5 digits number sometimes, because it generates random values between 0 and 999999.
Use the following snippet for generating random numbers in a range:
Random random = new Random();
minimum + random.nextInt(maximum - minimum + 1);

Generating a 2 digit integer [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I need to generate a random 2 digit number which will be concatenated to the end of a string. The number MUST be 2 digits (i.e. 00-99, nothing <10 is acceptable).
How can this be done using Java libraries in the simplest way possible?
A pretty simple way would be to generate two random integers separately, and then add them to the end of your string. That way anything from 1-9 would show up as 01-09.
Using this answer, Generating random integers in a specific range, you generate the two integers. Then create an empty string and add the two variables you used to store your random integers.
Psuedocode:
int a = RANDOMNUMBER
int b = RANDOMNUMBER
String number = "" + a + b

nextInt in java i don't understand how this works [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
I'm new to java and was viewing a tutorial and saw nextInt, the guy said that it was supposed to give me a number between -5 and 5 but i have two problems :
(r.nextInt(5 - -5) + -5)
1)In what order does it operate
2)The explanation that i found says that it doesn't accept negatives then why is it supposed to allow me to give me -5?
Thanks a lot.
The answer is unary negative and subtration. Usually, that's written as +. Like
(r.nextInt(5 + 5) + -5)
which is
(r.nextInt(10) - 5)
I assume this is for a Random, in which case it returns [0,10). Which if you subtract 5, is [-5,5).
What your code will do is generate a random integer between 0 and the specified value, and will then subtract 5 from the generated integer.

Cast problems between int and double [duplicate]

This question already has answers here:
math.random, only generating a 0?
(4 answers)
Closed 8 years ago.
This piece of code is giving the result I wanted
double a=Math.random()*100;
int b=(int)a;
System.out.println(b);
but when I did for the same thing this way, it is giving zero always
int a=(int)Math.random()*100;
System.out.println(a);
As far as I know typecasting will store the bigger data-type to small. but in the later code, I'm gettig zero every single time I run the program.
(int)Math.random()*100; means:
cast the value of 'Math.random()' to int and then multiple by 100. Since Math.random returns a number between 0 and 1 casting to int will always chop off the decimal path and give you 0.
The correct way to do it is
(int)(Math.random()*100);
Try with,
int a=(int)(Math.random()*100);
System.out.println(a);
Math.random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
Type casting is both right-to-left associative, and has a higher precedence than multiplication.
Source
Let me break it down a bit.
Like any other operator, a type cast has a certain level of priority attached to it. Certain operators have higher priority than others, and certain operators associate with their arguments in a certain way. For example, numerical operations are typically left-to-right associative; that is, with operators of an equal priority, one can parenthesize them from the left and get the same result.
Example:
5 * 5 * 5 / 3 + 5 -> (((5) * 5) * 5) / 3) + 5
Right-to-left associativity would allow you to parenthsize the operations from the right to achieve the same result.
Example:
int x;
int y;
int z;
x = y = z = 10 -> x = (y = (z = (10))
Type casting, much like assignment, is right-to-left associative, so it's going to essentially use the rightmost argument to satisfy its closest association, then progress backwards through the chain until you reach the ultimate goal.
This means that you could write this as valid syntax, although it would be very strange:
Object foo = (Object)(Number)(float)Math.random();
First, we cast our result from a double to a float, then to a Number, then to an Object (which is totally redundant, but possible).
The priority bit in particular is what causes the multiplication to apply last in this chain of events.
Bear in mind, in no one level of priority does the language intermingle associativity. That means an operator at level 1 priority associates in a specific way, and operators in level 2 operate in a specific way.
So, we come now to your expression:
int a = (int) Math.random() * 100;
Casting has a priority level of 3. The mathematical operator * has a priority level of 4. So, Java sees your statement like this:
int a = ((int) Math.random()) * 100;
The parentheses are there for extra clarity. (Note that parentheses have the highest priority.)
What you want to do, as explained more tersely in other answers, is use the parentheses to force your intended priority instead of letting Java decide. So, you would write this instead:
int a = (int) (Math.random() * 100);
This forces Java to evaluate the multiplication before the cast, since the parentheses have a higher priority than the cast.
Because the cast to int happens before the multiplication and as Math.random() generates a number between 0 (inclusive) and 1 (exclusive), it is rounded to 0.
You are casting before multiplying here...
Math.random() will generate number between 0 and 1 and will be rounded to 0 before multiplying with 100.
(int)(Math.random()*100) will behave as you want.
Consider using java.util.Random:
Random random = new Random();
int value = random.nextInt(100);
System.out.println(value);
Random is thread-safe, whereas Math.Random() is not.
When testing, you can feed a Random the same seed to generate reproducible pseudorandom numbers. You can't with Math.Random().
and more.
See more here: Math.random() versus Random.nextInt(int)
use this :
int a=(int)(Math.random()*100);
System.out.println(a);

Java math random inclusive 1 [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Write a truly inclusive random method for javascript
(10 answers)
Closed 9 years ago.
What is the easiest way to include 1 using Math.random function?
Since the default is number between inclusive 1 and exclusive 0.
I am going to use my the rand function a lot of times in my code that is why i need an even probability of getting numbers between 0 and 1 [0,1] , inclusive 0 and inclusive 1.
Thanks!
Edit:
Sorry, big mistake. Exclusive 1, inclusive 0.

Categories