Java: random long number in 0 = x n range
Starting from Java 7 (or Android API Level 21 = 5.0+) you could directly use ThreadLocalRandom.current().nextLong(n)
(for 0 ≤ x < n) and ThreadLocalRandom.current().nextLong(m, n)
(for m ≤ x < n). See @Alex's answer for detail.
If you are stuck with Java 6 (or Android 4.x) you need to use an external library (e.g. org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)
, see @mawaldne's answer), or implement your own nextLong(n)
.
According to Random
documentation, nextInt
is implemented as
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException("bound must be positive");
if ((bound & -bound) == bound) // i.e., bound is a power of 2
return (int)((bound * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % bound;
} while (bits - val + (bound-1) < 0);
return val;
}
So we may modify this to perform nextLong
:
long nextLong(Random rng, long bound) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % bound;
} while (bits-val+(bound-1) < 0L);
return val;
}
Java: Random long value in an interval
If you want range based long values then do the below:
long LOWER_RANGE = 0; //assign lower range value
long UPPER_RANGE = 1000000; //assign upper range value
Random random = new Random();
long randomValue = LOWER_RANGE +
(long)(random.nextDouble()*(UPPER_RANGE - LOWER_RANGE));
Creating random numbers with no duplicates
The simplest way would be to create a list of the possible numbers (1..20 or whatever) and then shuffle them with Collections.shuffle
. Then just take however many elements you want. This is great if your range is equal to the number of elements you need in the end (e.g. for shuffling a deck of cards).
That doesn't work so well if you want (say) 10 random elements in the range 1..10,000 - you'd end up doing a lot of work unnecessarily. At that point, it's probably better to keep a set of values you've generated so far, and just keep generating numbers in a loop until the next one isn't already present:
if (max < numbersNeeded)
{
throw new IllegalArgumentException("Can't ask for more numbers than are available");
}
Random rng = new Random(); // Ideally just create one instance globally
// Note: use LinkedHashSet to maintain insertion order
Set<Integer> generated = new LinkedHashSet<Integer>();
while (generated.size() < numbersNeeded)
{
Integer next = rng.nextInt(max) + 1;
// As we're adding to a set, this will automatically do a containment check
generated.add(next);
}
Be careful with the set choice though - I've very deliberately used LinkedHashSet
as it maintains insertion order, which we care about here.
Yet another option is to always make progress, by reducing the range each time and compensating for existing values. So for example, suppose you wanted 3 values in the range 0..9. On the first iteration you'd generate any number in the range 0..9 - let's say you generate a 4.
On the second iteration you'd then generate a number in the range 0..8. If the generated number is less than 4, you'd keep it as is... otherwise you add one to it. That gets you a result range of 0..9 without 4. Suppose we get 7 that way.
On the third iteration you'd generate a number in the range 0..7. If the generated number is less than 4, you'd keep it as is. If it's 4 or 5, you'd add one. If it's 6 or 7, you'd add two. That way the result range is 0..9 without 4 or 6.
Java - Generates random numbers and classify them for each value
Run the for loop 24 times instead of 25 times, since if i = 24, there is no array value at index randNum[24] (array indexes start at 0) (when you do i+1 inside the if statement).
for (int i = 0; i < 24; i++)
{
//your if-else blocks
}
Java Generate Random Number Between Two Given Values
You could use e.g. r.nextInt(101)
For a more generic "in between two numbers" use:
Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;
This gives you a random number in between 10 (inclusive) and 100 (exclusive)
Generating a Random Number between 1 and 10 Java
As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.
Generally speaking, if you need to generate numbers from min
to max
(including both), you write
random.nextInt(max - min + 1) + min
Generating Unique Random Numbers in Java
- Add each number in the range sequentially in a list structure.
- Shuffle it.
- Take the first 'n'.
Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.
import java.util.ArrayList;
import java.util.Collections;
public class UniqueRandomNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) list.add(i);
Collections.shuffle(list);
for (int i=0; i<3; i++) System.out.println(list.get(i));
}
}
The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single Random
instance.
That is what is causing the numbers to be identical. A Random
instance is seeded by the current time in milliseconds. For a particular seed value, the 'random' instance will return the exact same sequence of pseudo random numbers.
Related Topics
Java Wait for Thread to Finish
How to Enumerate All Classes in a Package and Add Them to a List
A Regex to Match a Substring That Isn't Followed by a Certain Other Substring
How to Get the File Name from a String Containing the Absolute File Path
Java Division by Zero Doesnt Throw an Arithmeticexception - Why
Comparing Float/Double Values Using == Operator
Drawing an Object Using Getgraphics() Without Extending Jframe
What Does an Assignment Expression Evaluate to in Java
Running Multiple Launch Configurations at Once
"Int Cannot Be Dereferenced" in Java
Java Date - Insert into Database
How to Make My Swingworker Example Work Properly
Bidirectional Multi-Valued Map in Java
Consistency of Hashcode() on a Java String
How to Obtain Jni Interface Pointer (Jnienv *) for Asynchronous Calls