Implement Java util. Random. nextInt
This function is Java util. Random. It returns a pseudo-random int evenly distributed between 0 and a given n. unfortunately, I didn't get it
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; }
My question is:
>Why deal with the situation where n is two powers in particular? Just for the show? Why reject the number of bits val (n-1) < 0?
Solution
Next, random bits are generated
>When n is a power of 2, random integers in this range can be generated by generating random bits (I assume that 31 is always generated and some are thrown for reproducibility) This code path is relatively simple. I think this is a common example, so in this case, it is worth a special "fast path" > When n is not a power of 2, it discards the number at the "top" of the range so that the random number is evenly distributed For example Imagine we have n = 3, imagine we use 3 bits instead of 31 bits So bits are randomly generated numbers from 0 to 7 So can you generate a fair random number there? Answer: if the bit is 6 or 7, we discard it and generate a new one