One of the problems in the "2016 International APL Problem Solving Competition (General Computing Category)" was as follows
Write an APL function named 'winner' which
- takes a right argument of a 5x5 character matrix representing a Teeko board
- if there is a winner, returns the appropriate character for the winner, otherwise returns the character representing an unoccupied space
The competition was won by Joshua David and he briefly goes over his solution in this video, but elides most of the details.
A winner can be 4 in a row - either horizontally, vertically, or diagonally - or a square cluster of 4. Below is my attempt at writing this winner
function in both J and BQN.
At the time of writing, I have only been toying around with J for a few months, and only about a week with BQN, so there's likely to better ways to solve this (particularly with BQN).
Winner =. {{
board =. y
filler =. {. ; (\: #@>) </.~ , board
players =. filler -.~ ~. , board
Four =. +./ @ 4 = +/"1 @ (players =/ ])
row =. Four board
col =. Four |: board
quad =. Four ,/ (2 2) ,;._3 board
diagL =. Four |: /. board
diagR =. Four |: /. |. board
result =. 1 ,~ +./"1 (row ,. col ,. quad ,. diagR ,. diagL)
{. result # (players , filler)
}}
([: (; Winner) 5 5 $ ])@> cutLF 0 : 0
......XXXX.OO....OO......
.O....O.X.XO.X..O..X.....
.......XX.OOXX..OO.......
.......XX..OOXX.OO.......
......X...OOX...OOX.....X
.........O...O...OXX.OXX.
..XX.XX..........OO..OO..
)
Winner ← {
board ← 𝕩
filler ← ⌈´⊸=∘⊒⊸/ ⥊ board
players ← ¬∘∊⟜filler⊸/ ⍷ ∾´ ⥊ board
Four ← ∨´˘ 4 =˘ +´⎉1 ∘ (players =⌜ ⊣)
Quads ← ∾˝·⥊⎉2 2‿2⊸↕
Diags ← 4↑ 1⌽·∾˝ 4⊸↕⎉1 ∘ (⍉ ¯1 ⌽˘ ↕∘≠ ⌽˘ ⊢)
row ← Four board
col ← Four ⍉ board
quad ← Four Quads board
diagR ← Four Diags board
diagL ← Four Diags ⌽ board
result ← 1 ∾˜ ∨˝ ∾˘ ⟨col,row,quad,diagR,diagL⟩
⊑ result / players ∾ filler
}
{
•Out ((⥊ " "⊸∾∘∾⟜(@+10)˘) ∾ "result: " ∾ Winner) 5‿5 ⥊ 𝕩
•Out 9 ⥊ "="
}¨ ⟨
"......XXXX.OO....OO......",
".O....O.X.XO.X..O..X.....",
".......XX.OOXX..OO.......",
".......XX..OOXX.OO.......",
"......X...OOX...OOX.....X",
".........O...O...OXX.OXX.",
"..XX.XX..........OO..OO..",
⟩