Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 1m5s
19 lines
847 B
APL
19 lines
847 B
APL
⍝ N-Queens — count solutions to placing N non-attacking queens on N×N
|
||
⍝
|
||
⍝ A solution is encoded as a permutation P of 1..N where P[i] is the
|
||
⍝ column of the queen in row i. Rows and columns are then automatically
|
||
⍝ unique (it's a permutation). We must additionally rule out queens
|
||
⍝ sharing a diagonal: |i-j| = |P[i]-P[j]| for any pair.
|
||
⍝
|
||
⍝ Backtracking via reduce — the classic Roger Hui style:
|
||
⍝ queens ← {≢{⍵,¨⍨↓(0=∊(¨⍳⍴⍵)≠.+|⍵)/⍳⍴⍵}/(⍳⍵)⍴⊂⍳⍵}
|
||
⍝
|
||
⍝ Plain reading:
|
||
⍝ permute 1..N, keep those where no two queens share a diagonal.
|
||
⍝
|
||
⍝ Known solution counts (OEIS A000170):
|
||
⍝ N 1 2 3 4 5 6 7 8 9 10
|
||
⍝ q(N) 1 0 0 2 10 4 40 92 352 724
|
||
|
||
queens ← {≢({(i j)←⍺⍵ ⋄ (|i-j)≠|(P[i])-(P[j])}⌿permutations ⍵)}
|