Page 1 of 1

CryptRandom puzzle

Posted: Sat Oct 08, 2016 12:01 pm
by firace
See the below snippet.
I'm not able to figure out why total is not equal to 6000, but sometimes higher, and sometimes lower ? Am I off by one somewhere? (PB 5.31, Windows 8.1, 32-bit)

Note: I created balancedCryptRandom() so that a power of 2 minus 1 is always passed to CryptRandom(), as per the help file.

Code: Select all


OpenCryptRandom()
procedure balancedCryptRandom(x)    
  j=1
  repeat :  j*2  :  until j>x  
  
  Repeat
    dice = CryptRandom(j-1) + 1
  Until dice <= x
  
  ProcedureReturn dice
  
EndProcedure


dim results(6)
for i=1 to 6000
  results(balancedCryptRandom(6)) + 1 
;   jj + 1
next

for i=1 to 6
  debug "Value " + i + " occurred: " + results(i) + " times."
  
  total + results(i)
next

debug total
; debug jj


Re: CryptRandom puzzle

Posted: Sat Oct 08, 2016 4:17 pm
by Sirius-2337
The problem is this line:

Code: Select all

results(balancedCryptRandom(6)) + 1
It is only a shortcut and will be expanded to this line by the compiler:

Code: Select all

results(balancedCryptRandom(6)) = results(balancedCryptRandom(6)) + 1
Now you see the problem I guess.

You need to write it like this:

Code: Select all

a = balancedCryptRandom(6)
  results(a) + 1

Re: CryptRandom puzzle

Posted: Sun Oct 09, 2016 1:42 am
by firace
Awesome! Great explanation, thanks.