Skip to content

Instantly share code, notes, and snippets.

@lukasvermeer
Created January 24, 2019 13:33
Show Gist options
  • Save lukasvermeer/f772a942018c4f834f9eafa7cfc12bda to your computer and use it in GitHub Desktop.
Save lukasvermeer/f772a942018c4f834f9eafa7cfc12bda to your computer and use it in GitHub Desktop.
Simple Julia simulation to solve puzzle posed in https://www.twitter.com/jben0/status/1088146700735139840
# simulation to solve puzzle posed in https://www.twitter.com/jben0/status/1088146700735139840
k = 10
# enumerate all potential combinations of flips
# (also copies first two students to end of the string to fake a circle)
f = map(x->(x^2)[1:k+2],[ bitstring(n)[65-k:64] for n in 0:2^k-1 ])
# condition on at least one student with heads on either side
c = filter(l->size(collect(eachmatch(r"1.1",l)),1)>0,f)
# alternative interpretation: condition on only one student in the group matching
# c = filter(l->size(collect(eachmatch(r"1.1",l,overlap=true)),1)==1,f)
# collect all flips for students between heads
r = map(x->collect(m[1] for m in eachmatch(r"1(.)1",x,overlap=true)),c)
# compute probability of heads over all tables
p1 = sum(x->sum(y->y=="1",x),r) / sum(x->size(x)[1],r)
println("probability of heads over all tables: ", p1)
# compute average probability of heads per table
p2 = sum(x->sum(y->y=="1",x)/size(x)[1],r) / size(r)[1]
println("average probability of heads per table: ", p2)
@lukasvermeer
Copy link
Author

Result:

$> julia circle_flips.jl 
probability of heads over all tables: 0.5
average probability of heads per table: 0.42568422717924387

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