-
-
Save rightfold/2a2453c5e47cfc066e95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
queens←{ ⍝ The N-queens problem. | |
search←{ ⍝ Search for all solutions. | |
(⊂⍬)∊⍵:0⍴⊂⍬ ⍝ stitched: abandon this branch. | |
0=⍴⍵:rmdups ⍺ ⍝ all done: solution! | |
(hd tl)←(↑⍵)(1↓⍵) ⍝ head 'n tail of remaining ranks. | |
next←⍺∘,¨hd ⍝ possible next steps. | |
rems←hd free¨⊂tl ⍝ unchecked squares. | |
⊃,/next ∇¨rems ⍝ ... in following ranks. | |
} | |
cvex←(1+⍳⍵)×⊂¯1 0 1 ⍝ Checking vectors. | |
free←{⍵~¨⍺+(⍴⍵)↑cvex} ⍝ Unchecked squares. | |
rmdups←{ ⍝ Ignore duplicate solution. | |
rots←{{⍒⍵}\4/⊂⍵} ⍝ 4 rotations. | |
refs←{{⍋⍵}\2/⊂⍵} ⍝ 2 reflections. | |
best←{(↑⍋⊃⍵)⊃⍵} ⍝ best (=lowest) solution. | |
all8←,⊃refs¨rots ⍵ ⍝ all 8 orientations. | |
(⍵≡best all8)⊃⍬(,⊂⍵) ⍝ ignore if not best. | |
} | |
fmt←{ ⍝ Format solution. | |
chars←'·⍟'[(⊃⍵)∘.=⍳⍺] ⍝ char array of placed queens. | |
expd←1↓,⊃⍺⍴⊂0 1 ⍝ expansion mask. | |
⊃¨↓↓expd\chars ⍝ vector of char matrices. | |
} | |
squares←(⊂⍳⌈⍵÷2),1↓⍵⍴⊂⍳⍵ ⍝ initial squares | |
⍵ fmt ⍬ search squares ⍝ all distinct solutions. | |
} | |
queens 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment