Skip to content

Instantly share code, notes, and snippets.

@rodrigogiraoserrao
Last active July 17, 2020 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodrigogiraoserrao/1a6543226fdd8d51dc4c669acabf76ad to your computer and use it in GitHub Desktop.
Save rodrigogiraoserrao/1a6543226fdd8d51dc4c669acabf76ad to your computer and use it in GitHub Desktop.
:Namespace GameOf24
⍝ Generalized solver for the "game of 24".
Solve ← {
⍝ Dyadic function to find ways of building ⍺ with the numbers in ⍵
(reprs values) ← Combine⊂⍵
mask ← ⍺=∊values
(mask/reprs) (mask/values)
}
Combine ← {
⍝ Recursive dyadic function combining the numbers ⍵ which have been obtained by the expressions ⍺
⎕DIV←1
⍺←⍕¨¨⍵ ⍝ default string representations of input numbers
1=l←≢⊃⍵: ⍺ ⍵ ⍝ if no more numbers to combine, return
C ← { ⍝ Combine two numbers of ⍵ with the dyadic function in ⍺
(r v) ← ⍵
(li ri) ← ↓⍉idx⌿⍨sub← ≠v[idx]
newv ← v[li] (⍎⍺) v[ri]
oldv ← v[sub⌿unused]
values ← ↓newv,oldv
reprs ← ↓r[sub⌿unused],⍨↓(↑sub/⊂⍺),(↑r[li]),' ',↑r[ri]
reprs values
}
idx ← (~0=(1+l)|⍳l*2) ⌿ ↑,⍳l l
unused ← idx ~⍨⍤1 1 ⍳l
(a w) ← Unpack, '+-×÷' ∘.C ↓⍉↑⍺ ⍵
u←≠w
a ∇⍥(u∘/) w
}
Unpack ← { ⍝ unpack pairs of nested results
⊃{(wl wr)←⍵ ⋄ (al ar)←⍺ ⋄ (al,wl)(ar,wr)}/⍵
}
IsEmpty ← ((0⍴⊂,0)≡⊃∘⌽) ⍝ Check if a return from Solve is empty
CountSolvable ← {
⍝ Given a target integer ⍵ check how many 4 unique-digit inputs are solvable
inps ← ({∧/2</⍵}¨inps)/inps←,1+⍳4⍴9
1⊥~IsEmpty¨ ⍵ Solve¨ inps
}
∇ counts ← {allowRepeated} StudySolvability upTo
:If 900⌶⍬
allowRepeated ← 0
:EndIf
:If allowRepeated
filter ← {∧/2≤/⍵}
:Else
filter ← {∧/2</⍵}
:EndIf
⎕← 'Starting the study.'
(reprs values) ← Unpack Combine∘⊂¨ inps←(filter¨inps)/inps←,1+⍳4⍴9
flat ← ∊values
⎕← 'Maximum attainable value is ', ⌈/flat
counts ← 1⊥⍉ (⍳upTo+1) ∘.= flat
∇ sp ← max Plot counts
sp ← ⎕new #.Causeway.SharpPlot
sp.XCaption ← 'Target'
sp.YCaption ← '# inputs solvable'
sp.LineGraphStyle ← #.Causeway.LineGraphStyles.XYPlot
sp.LineGraphStyle ← #.Causeway.LineGraphStyles.GridLines
sp.DrawLineGraph counts (xs←⍳≢counts)
sp.DrawLineGraph (xs ∘.⊢ max) xs
#.View sp
∇ BlogCode
⍝ Most of the code used throughout the blog post available at
⍝ https://mathspp.com/blog/24-game
uinps ← all/⍨ {∧/2</⍵}¨ all←,1+⍳4⍴9 ⍝ inputs with unique digits
nuinps ← all/⍨ {∧/2≤/⍵}¨ all ⍝ digits may repeat
r ← 24 IsEmpty⍤Solve¨ uinps ⍝ check inputs for which 24 fails
⎕← uinps/⍨r
r ← 24 IsEmpty⍤Solve¨ nuinps ⍝ check on how many non unique inputs 24 fails
⎕← ≢r
r ← 2 IsEmpty⍤Solve¨ nuinps ⍝ check inputs for which 2 fails
⎕← nuinps/⍨r
⍝ produce the markdown table
better ← (⍳13), 14, 15, 16, 18
r ← Combine∘⊂¨ nuinps
(reprs values) ← Unpack r
counts ← +⌿ values ∘.= better
(reprs uvalues) ← Unpack r/⍨ nuinps∊uinps
ucounts ← +⌿ uvalues ∘.= better
⎕← '|',(⍪better),'|',(⍕⍪ucounts),'|',(⍕⍪counts),'|'
:EndNamespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment