Skip to content

Instantly share code, notes, and snippets.

@vbauerster
Created May 5, 2014 19:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vbauerster/11545989 to your computer and use it in GitHub Desktop.
Save vbauerster/11545989 to your computer and use it in GitHub Desktop.
java.util.Random.nextInt(n)
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment