Java 7ThreadLocalRandom.current().nextLong(n)
(または Android API レベル 21 = 5.0+) 以降では、(0 ≤ x < nThreadLocalRandom.current().nextLong(m, n)
の場合) および (m ≤ x < n の場合)を直接使用できます。詳細については、 @Alexの回答を参照してください。
Java 6 (または Android 4.x)に行き詰まっている場合は、外部ライブラリを使用する必要があります (たとえばorg.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1)
、@mawaldneの回答を参照)、または独自のnextLong(n)
.
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html によると、次のようにnextInt
実装されています
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
したがって、これを変更して実行できますnextLong
。
long nextLong(Random rng, long n) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits-val+(n-1) < 0L);
return val;
}