Skip to content

Instantly share code, notes, and snippets.

@mweppler
Created November 6, 2011 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mweppler/1343256 to your computer and use it in GitHub Desktop.
Save mweppler/1343256 to your computer and use it in GitHub Desktop.
Ported from Wibit.net objective-c implementation
@_MT = Array.new
@_index = 0
@maskUnity = 0xffffffff # 32 bits
@maskHighestBit = 0x80000000 # Most significant bit;
@maskLowerBits = 0x7fffffff # Last 32 bits
def initializeGenerator seed
# Set first array value to be the seed
@_MT[0] = seed
1.upto(623) do |i|
@_MT[i] = @maskUnity & (1812433253 * (@_MT[i - 1] ^ (@_MT[i - 1] >> 30)) + i);
end
end
def generateNumbers
counter = 1
0.upto(@_MT.size - 2) do |i|
pieceOfClay = (@maskHighestBit & @_MT[i]) + (@maskLowerBits & (@_MT[i + 1] % 624))
tempIndex = (i + 397) % 624
@_MT[i] = @_MT[tempIndex] ^ (pieceOfClay >> 1)
if pieceOfClay % 2 != 0
@_MT[i] = @_MT[i] ^ (0x9908b0df)
end
end
end
def extractNumber
unless @_index != 0
generateNumbers
end
tinyDancer = @_MT[@_index]
# 11 steps to the right
tinyDancer = tinyDancer ^ (tinyDancer >> 11)
# 7 to the left and JUMP 2x
tinyDancer = tinyDancer ^ ((tinyDancer << 7) & (0x9d2c5680))
# and then back to the right, and 18 bits, with a hand on the hip
tinyDancer = tinyDancer ^ ((tinyDancer << 15) & (0xefc60000))
tinyDancer = tinyDancer ^ (tinyDancer >> 18)
# and then repeat
@_index = (@_index + 1) % 624
return tinyDancer
end
initializeGenerator (Time.now.to_i * 1000).to_i
puts "Your random number is #{extractNumber}\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment