This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am trying to generate a random number between a given range and 0.
The code given below helped me to generate a number between the given range.
(int)(Math.random() * 13 + 4);
Is it possible to modify this code to generate a value between 4 and 10 and also 0
use this for generate a value between 4 and 10
public static double getRandomDoubleBetweenRange(int 4, int 10){
double x = (Math.random()*((10-4)+1))+4;
return x;
}
I suspect that this is a homework question so I won't spoonfeed you with the correct answer but give you the tools you need to answer it yourself:
public static double 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.
Source: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#random--
Casting a double to an int performs a narrowing primitive conversion. In the range you use and for positive numbers, you can just treat it like a floor (removing the numbers after the decimal point).
If you want to know about the details, see: https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3
Something like this would do the cause.
//stream 3 random numbers from 0 to 10 and pick any of them
int random = new Random().ints(3, 0, 11).findAny().getAsInt();
//print it
System.out.println(random);
UPDATE 2:
// make a list of 0 and 4-10
List<Integer> list = Arrays.asList(0,4,5,6,7,8,9,10);
// used for picking random number from within a list
Random random = new SecureRandom();
// get random index element from a list
int randomNumber = list.get(random.nextInt(list.size()));
// print
System.out.println(randomNumber);
Related
I have to generate unique serial numbers for users consisting of 12 to 13 digits. I want to use random number generator in Java giving the system. Time in milliseconds as a seed to it. Please let me know about the best practice for doing so. What I did was like this
Random serialNo = new Random(System.currentTimeMillis());
System.out.println("serial number is "+serialNo);
Output came out as: serial number is java.util.Random#13d8cc98
For a bit better algorithm pick SecureRandom.
You passed a seed to the random constructor. This will pick a fixed sequence with that number. A hacker knowing the approximate time of calling, might restrict the number of attempts. So another measure is not using the constructor and nextLong at the same spot.
SecureRandom random = new SecureRandom​();
long n = random.nextLong();
A symmetric bit operation might help:
n ^= System.currentMillis();
However there is a unique number generation, the UUID, a unique 128 bits number, two longs. If you xor them (^) the number no longer is that unique, but might still be better having mentioned the circumstantial usage of random numbers.
UUID id = UUID.randomUUID();
long n = id.getLeastSignificantBits() ^ id.getMostSignificantBits();
Create a random number generator using the current time as seed (as you did)
long seed = System.currentTimeMillis();
Random rng = new Random​(seed);
Now, to get a number, you have to use the generator, rng is NOT a number.
long number = rng.nextLong();
According to the documentation, this will give you a pseudorandom number with 281.474.976.710.656 different possible values.
Now, to get a number with a maximum of 13 digits:
long number = rng.nextLong() % 10000000000000;
And to get a number with exactly 13 digits:
long number = (rng.nextLong() % 9000000000000) + 1000000000000;
First, import the Random class:
import java.util.Random;
Then create an instance of this class, with the current milliseconds as its seed:
Random rng = new Random(System.currentTimeMillis());
This line would generate an integer that can have up to 13 digits:
long result = rng.nextLong() % 10000000000000;
This line would generate an integer that always have 13 digits:
long result = rng.nextLong() % 9000000000000 + 1000000000000;
There are three ways to generate Random numbers in java
java.util.Random class
We can generate random numbers of types integers, float, double, long, booleans using this class.
Example :
//Random rand = new Random();
// rand_int1 = rand.nextInt(1000)
Math.random method : Can Generate Random Numbers of double type.
random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Example :
Math.random());
//Gives output 0.15089348615777683
ThreadLocalRandom class
This class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc
Example :
//int random_int1 = ThreadLocalRandom.current().nextInt();
// Print random integers
//System.out.println("Random Integers: " + random_int1);
This question already has answers here:
Getting N random numbers whose sum is M
(9 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
my output contains 3 textfields where when given N value (the doClick() function clicks 3 textfields automatically), then it randomly generates 3 numbers in the three textfields , My code is generating only random numbers , but i want those randomly generated numbers to be exactly add up to given N.
example : when N=20
then possible answers can be:
1.10,10,0 i.e. (textfield1 show 10, textfield2 show 10, textfiled3 show 0, whose sum adds up to given N )
2.15,3,2
3.10,5,5
random numbers can be any positive integer but it should add up to given N.
Any help please.
You could use Math.random() instead of the Random class. Math.random() returns a double between 0 and 1. So the only thing you have to do is multiply the result of Math.random() with N. The next number would be N minus your result from the subtraction of N and the previous result.
final int N = 20;
final int result0 = (int) (Math.random() * N);
final int result1 = (int) (Math.random() * (N - result0));
final int result2 = N - result0 - result1;
EDIT: You could than choose the first, second and third parameter randomly too.
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am trying to print a random number between 80 and 100.
However when I print out this number I am getting numbers over 100?
Random num = new Random();
int percent = 80 + num.nextInt(100);
System.out.println(percent);
Can you try something like this
There are two approach below
int resultNumber = ThreadLocalRandom.current().nextInt(80, 100 + 1);
System.out.println(resultNumber);
Random num = new Random();
int min =80;
int max=100;
System.out.println(num.nextInt(max-min) + min);
Explanation
From the documentation of Random#nextInt(int):
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), [...]
So your call
num.nextInt(100);
Generates numbers between 0 (inclusive) and 100 (exclusive). After that you add 80 to it. The resulting range for your percent is thus 80 (inclusive) to 180 (exclusive).
Solution
In order to get a number from 80 to 100, what you actually want to do is to generate a number from 0 to 20 and add that on top of 80. So
int percent = 80 + num.nextInt(20);
The general formula is
int result = lowerBound + random.nextInt(upperBound - lowerBound);
Notes
Favor using ThreadLocalRandom over new Random(), it is faster because it sacrifices thread-safety (which you most likely do not need). So:
Random num = ThreadLocalRandom.current();
It actually also has an additional nextInt(int, int) method for exactly this use case. See the documentation:
Returns a pseudorandom int value between the specified origin (inclusive) and the specified bound (exclusive).
The code would then just be:
int percent = ThreadLocalRandom.current().nextInt(80, 100);
All my examples so far assumed that 100 is exclusive. If you want it to be inclusive, just add 1 to it. So for example
int percent = ThreadLocalRandom.current().nextInt(80, 101);
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
double random1 = Math.random() * 9 + -9;
double random2 = Math.random() * -9 + 9;
I need randomly generated numbers ranging from -9 to 9 using Math.random. When I use this code I have here it only prints the first number as a negative number.I've ran this multiple times and still the first number is always negative while the second is positive. How can I fix this to be more random? Thanks
Math.random() generates a number between 0 and 1.
How about multiplying by 18 and then subtracting 9?
From jdk-7 you can use ThreadLocalRandom
public int nextInt(int origin, int bound)
Returns a pseudorandom int value between the specified origin (inclusive) and the specified bound (exclusive).
ThreadLocalRandom.current().nextInt(-9, 10) // will generate from -9>=x<10
When you want a value between a number min and a number max :
Math.random() * ((max - min) + 1) + min
This question already has an answer here:
Select a random value from an Array
(1 answer)
Closed 8 years ago.
I'm writing a program that generates co-primes of a number.
Now for example a number 'A' has 50 co-primes, my objective is to randomly select a co-prime from the list of all co-primes generated for the number A.
Again for example:
consider a number 15, it has co-primes - {1, 2, 4, 7, 8, 10, 11, 13, 14}. So now i have to select randomly from these values. Likewise, if i generate an array of any values, then how to randomly select from this array.
So in general my question is how to generate a random number from the array of numbers that i have. Now, those numbers in the array can be anything. Like not necessarily natural numbers, or prime numbers, etc.
So is there any java function to do so. I've burnt my brain searching the internet, but didn't find one. I usually go for finding result on google, rather than asking quetions on forums. But when one gets exhausted, it's better to ask experts out there who might have faced similar problems.
Thanks in advanced!!
Is that what you want ?
int[] arr = { 1,5,9,3,2,7 };
Random rd = new Random();
int dice = arr[rd.nextInt(arr.length)];
You can use the java.util.Random class for this:
public int chooseRandom(int[] coPrimes) {
//Creates the Random instance
Random randomizer = new Random();
//Generate a random integer between 0 and the length of the array (exclusive)
int value = randomizer.nextInt(coPrimes.length);
//Return the element at that generated index
return coPrimes[value];
}