Zarrab

Java RNG

Sep 20th, 2011
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. public class JavaRandom {
  2.         private static ulong Mask = (1UL << 48) - 1UL;
  3.         private static ulong Multiplier = 0x5DEECE66DUL;
  4.         private static ulong AddEnd = 0xBUL;
  5.         private static ulong Seed = 0UL;
  6.  
  7.         public JavaRandom(ulong seed) {
  8.             SetSeed(seed);
  9.         }
  10.  
  11.         public void SetSeed(ulong seed) {
  12.             Seed = (seed ^ Multiplier) & Mask;
  13.         }
  14.  
  15.         public int Next(int bits) {
  16.             ulong oldseed, nextseed;
  17.             do {
  18.                 oldseed = Seed;
  19.                 nextseed = (oldseed * Multiplier + AddEnd) & Mask;
  20.  
  21.                 if (Seed == oldseed) {
  22.                     Seed = nextseed;
  23.                     break;
  24.                 }
  25.             } while (true);
  26.  
  27.             return (int)(nextseed >> (48 - bits));
  28.         }
  29.  
  30.         public int NextInt(int max) {
  31.             if ((max & -max) == max)
  32.                 return (int)((max * (long)Next(31)) >> 31);
  33.  
  34.             int bits, val;
  35.             do {
  36.                 bits = Next(31);
  37.                 val = bits % (int)max;
  38.             } while (bits - val + (max - 1) < 0);
  39.             return val;
  40.         }
  41.  
  42.         public long NextLong() {
  43.             return ((long)Next(32) << 32) + Next(32);
  44.         }
  45.     }
Advertisement
Add Comment
Please, Sign In to add comment