mercredi 4 octobre 2017

Java. `Random.nextLong()` with defined upper bound

There is a Random.nextInt(int n), where n sets the (exclusive) upper bound. There is a Random.nextLong() but I could not find a Random.nextLong(long n).

Is there an equivalent to Random.nextInt(int n)?


I guess if no equivalent of Random.nextLong(long n) exists I could do something like

long x;
do
{
   x = rand.nextLong(n);
} while (x >= 0 && x < n);

but that could be very slow for small n. Or maybe

x = rand.nextLong(n);
if (x >= n)
{
   x %= n;
}

but that would be biased. Or even

x = rand.nextLong(n);
double ratio = x / Long.MAX_VALUE;
x =  Math.round(ratio * n);

What method should I use?




Aucun commentaire:

Enregistrer un commentaire