Advertisement
ranisalt

Pure Lua Mersenne Twister

Feb 2nd, 2014
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.18 KB | None | 0 0
  1. --[[
  2.     `mt` : mersenne twisted pseudorandom number array
  3.     `index` : index of the current `mt` position
  4.     others : indexing global functions for faster performance
  5. ]]
  6. local mt, index, band, bor, bxor, lshift, rshift = {}, 0, bit.band, bit.bor, bit.bxor, bit.lshift, bit.rshift
  7.  
  8. --[[
  9.     initializes `mt` with custom seed or current time
  10. ]]
  11. local init_rand = function(s)
  12.     if s == nil then
  13.         s = os.time()
  14.     end
  15.     mt[0] = band(s, 0xffffffff)
  16.     for index = 1, 623 do
  17.         mt[index] = band(0x6c078965 * bxor(mt[index - 1], rshift(mt[index - 1], 30)) + index, 0xffffffff)
  18.     end
  19. end
  20.  
  21. --[[
  22.     extracts random number from `mt` with tampering
  23. ]]
  24. local rand = function()
  25.     local matrix, y = {0, 0x9908b0df}
  26.     if index == 0 then
  27.         init_rand()
  28.         for i = 0, 623 do
  29.             y = bor(band(mt[i], 0x80000000), band(mt[(i + 1) % 624], 0x7ffffff))
  30.             mt[i] = bxor(mt[(i + 397) % 624], rshift(y, 1), matrix[band(y, 1) + 1])
  31.         end
  32.     end
  33.     index = (index + 1) % 624
  34.     y = mt[index]
  35.    
  36.     --[[ tampering ]]
  37.     y = bxor(y, rshift(y, 11))
  38.     y = band(bxor(y, lshift(y, 7), 0x9d2c5680))
  39.     y = band(bxor(y, lshift(y, 15), 0xefc60000))
  40.     y = bxor(y, rshift(y, 18))
  41.    
  42.     return y % 0xffffffff
  43. end
  44.  
  45. for _ = 1, 10000000 do
  46.     rand()
  47. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement