Unbias a random generator: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: Changed to universal monadic solution) |
(→{{header|Haskell}}: Added examples) |
||
Line 681: | Line 681: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
The first task: |
|||
<lang haskell>import Control.Monad.Random |
<lang haskell>import Control.Monad.Random |
||
import Control.Monad |
import Control.Monad |
||
Line 687: | Line 687: | ||
randN :: MonadRandom m => Int -> m Int |
randN :: MonadRandom m => Int -> m Int |
||
randN n = fromList [(0, fromIntegral n-1), (1, 1)] |
randN n = fromList [(0, fromIntegral n-1), (1, 1)]</lang> |
||
Examples of use: |
|||
-- works for any random generator |
|||
<pre>λ> replicateM 20 (randN 2) |
|||
⚫ | |||
[0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0,0] |
|||
⚫ | |||
λ> replicateM 20 (randN 5) |
|||
[0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,1,0,1,0]</pre> |
|||
The second task. Returns the unbiased generator for any given random generator. |
|||
⚫ | |||
⚫ | |||
y <- g |
y <- g |
||
if x /= y then return y else unbias g |
if x /= y then return y else unbias g</lang> |
||
Examples of use: |
|||
<pre>λ> replicateM 20 (unbiased (randN 5)) |
|||
[0,0,1,0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,1,0] |
|||
λ> replicateM 20 (unbias (fromList [(True,10),(False,1)])) |
|||
[True,True,False,True,True,True,False,True,False,True,True,False,False,True,False,True,True,False,False,True]</pre> |
|||
The third task: |
|||
main = forM_ [3..6] showCounts |
<lang Haskell>main = forM_ [3..6] showCounts |
||
where |
where |
||
showCounts b = do |
showCounts b = do |