2022.10.06 02:34 AM
The One Hundred Prisoners problem has a famously counter-intuitive solution, nicely explained on YouTube:
https://www.youtube.com/watch?v=iSNsgj1OCLA
Exploring it in q is illuminating!
George Berkeley kicked this off in the Vector Dōjō :
A problem I found interesting, and maybe you will too...You can view a vectorv = (1 0 2 3 5 6 4)
as a permutation, i.e. given an indexi
, the permutation sendsi
tov[i]
. If we apply the permutation multiple times, then eventually we end up where we started. In fact, if we look atv
, we can see it breaks down into the following cycles:0 -> 1 -> 0 2 -> 2 3 -> 3 4 -> 5 -> 6 -> 4Given a permutation, return the number of cycles! (so 4 for the givenv
)
q)v:1 0 2 3 5 6 4
q)v scan 0
0 1
q)(v scan)each 0 2 3 4
0 1
,2
,3
4 5 6
q)(v scan)each v
1 0
0 1
,2
,3
5 6 4
6 4 5
4 5 6
0 1
and 1 0
are the same cycle. Sorting each cycle lets us remove duplicates and count.q)distinct(asc v scan)each v
`s#0 1
`s#,2
`s#,3
`s#4 5 6
q)count distinct(asc v scan)each v
4
q)max(count v scan)each v
3
q)max{(count x scan)each x} -100?100
44
q)max{(count x scan)each x} -100?100
55
q)max{(count x scan)each x} -100?100
90
q)show q:-10?10 / test
5 0 1 9 2 6 8 4 7 3
q)is:(#[;0]count@;::;til count@)@\: / initial state
q)is q
0 0 0 0 0 0 0 0 0 0
5 0 1 9 2 6 8 4 7 3
0 1 2 3 4 5 6 7 8 9
q)step:{[c;p;i] if[count i;c[r]:count r:p scan i 0];(c;p;where not c)} .
q)step is q
8 8 8 0 8 8 8 8 8 0
5 0 1 9 2 6 8 4 7 3
3 9
q)p:-100?100
q)\t:1000 max(count p scan)each p
134
q)\t:1000 max first step over is p
13
q)-1+ count step scan is v
4
q)-1+ count step scan is p
6
2022.10.06 11:29 AM
Brilliant content @SJT
Here's to many more Vector Dōjō events in the future!
Kudos to all involved 👏
EMEA
Tel: +44 (0)28 3025 2242
AMERICAS
Tel: +1 (212) 447 6700
APAC
Tel: +61 (0)2 9236 5700
KX. All Rights Reserved.
KX and kdb+ are registered trademarks of KX Systems, Inc., a subsidiary of FD Technologies plc.