Skip to content

Instantly share code, notes, and snippets.

@brettrowberry
Last active June 9, 2019 05:29
Show Gist options
  • Save brettrowberry/46d79c3a597a89b771f58e52c39f0dc5 to your computer and use it in GitHub Desktop.
Save brettrowberry/46d79c3a597a89b771f58e52c39f0dc5 to your computer and use it in GitHub Desktop.
This gives the probability of streaks of length `streakLength` in a binary string of length `bits`.
open System
let probabilityOfStreaks bits streakLength =
let matches bits streakLength =
let stringsOfLength bits =
let intToBinaryString width (number: int) =
Convert.ToString (number, 2)
|> (fun s -> s.PadLeft(width, '0'))
seq { 0.0 .. 1.0 .. (2.0 ** float bits - 1.0) }
|> Seq.map (fun f -> intToBinaryString bits (int f))
let isMatch n (s: string) =
let has_n_0s =
s.Split([|'1'|], StringSplitOptions.RemoveEmptyEntries)
|> Array.contains (String.replicate n "0")
let has_n_1s =
s.Split([|'0'|], StringSplitOptions.RemoveEmptyEntries)
|> Array.contains (String.replicate n "1")
if has_n_0s || has_n_1s
then true
else false
stringsOfLength bits
|> Seq.filter (fun s -> isMatch streakLength s )
|> Seq.length
float (matches bits streakLength) / 2. ** float bits |> sprintf "%.4f"
#time
probabilityOfStreaks 15 5
#time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment