Skip to content

Instantly share code, notes, and snippets.

@banthar
Created September 22, 2013 08:22
Show Gist options
  • Save banthar/6657894 to your computer and use it in GitHub Desktop.
Save banthar/6657894 to your computer and use it in GitHub Desktop.
import java.util.Random;
public class R {
private static long doRead(final Random r, final long rangeStart,
final long rangeEnd) {
long retVal = 0;
final long range = rangeEnd - rangeStart;
// Fill until we get to range
for (int i = 0; 1 << 8 * i < range; i++) {
int in = 0;
do {
in = r.nextInt(0x100);
// but be sure we don't exceed range
} while (retVal + (in << 8 * i) >= range);
retVal += in << 8 * i;
}
return retVal + rangeStart;
}
public static void main(final String... args) throws Exception {
final long[] result = new long[257];
final Random r = new Random();
final int n = 1000000;
for (int i = 0; i < n; i++) {
result[(int) doRead(r, 0, 257)]++;
}
for (int i = 0; i < 3; i++) {
System.out.println("p(" + i + ")=" + result[i] / (double) n);
}
System.out.println("...");
for (int i = 254; i < 257; i++) {
System.out.println("p(" + i + ")=" + result[i] / (double) n);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment