Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package jp.nekopippi;
- import java.io.IOException;
- import static java.lang.Math.abs;
- import java.util.Arrays;
- import java.util.Random;
- import java.util.stream.IntStream;
- import java.nio.ByteBuffer;
- import java.nio.channels.ByteChannel;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.nio.file.Files;
- import static java.nio.file.StandardOpenOption.READ;
- import org.junit.*;
- import static org.junit.Assert.*;
- public class PseudoRandomTest {
- private static ByteChannel urandom;
- private ByteBuffer mBuf;
- @BeforeClass
- public static void openUrandom() throws IOException {
- final Path p = Paths.get("/dev/urandom");
- urandom = Files.newByteChannel(p, READ);
- }
- @AfterClass
- public static void closeFiles() throws IOException {
- if (urandom != null) {
- urandom.close();
- }
- }
- @Before
- public void initBuffer() {
- mBuf = ByteBuffer.allocate(16);
- }
- @Test
- public void testFirst512Bits10Times() {
- assertEquals(
- IntStream.range(0, 10)
- .map(ignore -> {
- final long seed = getSeed();
- final Random prng1 = new Random(seed);
- final Random prng2 = new Random(seed);
- final long l1 = prng1.nextLong();
- final long l2 = prng2.nextLong();
- return Long.compare(l1, l2);
- })
- .reduce(0, (a, v) -> a + abs(v)),
- 0);
- }
- @Test
- public void testFirst65536Bits() {
- final long seed = getSeed();
- final Random prng1 = new Random(seed);
- final Random prng2 = new Random(seed);
- // 128 * 64 * 8 = 65536
- IntStream.range(0, 128).forEach(ignore -> {
- final long l1 = prng1.nextLong();
- final long l2 = prng2.nextLong();
- assertEquals(l1, l2);
- });
- }
- private final long getSeed() {
- mBuf.clear();
- try {
- urandom.read(mBuf);
- } catch (IOException e) {
- fail(e.toString());
- }
- mBuf.flip();
- final long seed = mBuf.getLong();
- return seed;
- }
- }
Add Comment
Please, Sign In to add comment