Skip to content

Instantly share code, notes, and snippets.

@benhowes
Created August 21, 2012 20:16
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 benhowes/3419008 to your computer and use it in GitHub Desktop.
Save benhowes/3419008 to your computer and use it in GitHub Desktop.
prove to your intuition that you cannot predict coin tosses any better than chance with a knowledge of the recent flips!
runs = 1000000
Math.RandomInteger = (n, m) ->
if not m then m = 1 # default range starts at 1
max = if n > m then n else m # doesn<q>t matter which value is min or max
min = if n is max then m else n # min is value that is not max
d = max - min + 1 # distribution range
Math.floor(Math.random() * d + min)
initBuffer = (len)->
buffer = new ArrayBuffer(len)
stack = new Uint8Array(buffer);
for i in [0..len] by 2
stack[i] = 0;
stack[i+1] = 1;
stack
normal = ()->
()->
0 #always choose 0
random = ()->
()->
Math.RandomInteger(0,1)
regress = ()->
stack = initBuffer(4)
overwrite = 0
(result)->
stack[(overwrite++%4)] = 0
sum = 0
for i in stack
sum += i
if sum is 2 then Math.RandomInteger(0,1)
else if sum > 2 then 0 #based on resent history guess differently
else 1
regressLong = ()->
stack = initBuffer(10)
overwrite = 0
(result)->
stack[(overwrite++%10)] = 0
sum = 0
for i in stack
sum += i
if sum is 2 then Math.RandomInteger(0,1)
else if sum > 2 then 0 #based on resent history guess differently
else 1
versions =
'normal' : normal()
'random' : random()
'regress 4' : regress()
'regress 10' : regressLong()
main = ()->
results = {}
for version of versions
results[version] = 0
prevResult = 0 #not fair, but nothing we can do...
for i in [1..runs]
result = Math.RandomInteger(0,1)
for version of versions
guess = versions[version](prevResult)
if guess is result
results[version]++
prevResult = result #propegate the result
if (i % 10000) is 0
console.log("#{i*100/runs}% complete")
#print out the results
for version of versions
console.log("variable #{version} was sucessful #{results[version]*100/runs}% of the time")
main()
@Mirey-zz
Copy link

Line 48 and Line 49 should be comparing sum to 5, not 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment