Guest User

Untitled

a guest
Dec 11th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. package jp.nekopippi;
  2.  
  3. import java.io.IOException;
  4. import static java.lang.Math.abs;
  5. import java.util.Arrays;
  6. import java.util.Random;
  7. import java.util.stream.IntStream;
  8. import java.nio.ByteBuffer;
  9. import java.nio.channels.ByteChannel;
  10. import java.nio.file.Path;
  11. import java.nio.file.Paths;
  12. import java.nio.file.Files;
  13. import static java.nio.file.StandardOpenOption.READ;
  14. import org.junit.*;
  15. import static org.junit.Assert.*;
  16.  
  17. public class PseudoRandomTest {
  18. private static ByteChannel urandom;
  19. private ByteBuffer mBuf;
  20.  
  21. @BeforeClass
  22. public static void openUrandom() throws IOException {
  23. final Path p = Paths.get("/dev/urandom");
  24. urandom = Files.newByteChannel(p, READ);
  25. }
  26.  
  27. @AfterClass
  28. public static void closeFiles() throws IOException {
  29. if (urandom != null) {
  30. urandom.close();
  31. }
  32. }
  33.  
  34. @Before
  35. public void initBuffer() {
  36. mBuf = ByteBuffer.allocate(16);
  37. }
  38.  
  39. @Test
  40. public void testFirst512Bits10Times() {
  41. assertEquals(
  42. IntStream.range(0, 10)
  43. .map(ignore -> {
  44. final long seed = getSeed();
  45. final Random prng1 = new Random(seed);
  46. final Random prng2 = new Random(seed);
  47.  
  48. final long l1 = prng1.nextLong();
  49. final long l2 = prng2.nextLong();
  50. return Long.compare(l1, l2);
  51. })
  52. .reduce(0, (a, v) -> a + abs(v)),
  53. 0);
  54. }
  55.  
  56. @Test
  57. public void testFirst65536Bits() {
  58. final long seed = getSeed();
  59. final Random prng1 = new Random(seed);
  60. final Random prng2 = new Random(seed);
  61. // 128 * 64 * 8 = 65536
  62. IntStream.range(0, 128).forEach(ignore -> {
  63. final long l1 = prng1.nextLong();
  64. final long l2 = prng2.nextLong();
  65. assertEquals(l1, l2);
  66. });
  67. }
  68.  
  69. private final long getSeed() {
  70. mBuf.clear();
  71. try {
  72. urandom.read(mBuf);
  73. } catch (IOException e) {
  74. fail(e.toString());
  75. }
  76. mBuf.flip();
  77. final long seed = mBuf.getLong();
  78. return seed;
  79. }
  80. }
Add Comment
Please, Sign In to add comment