Solving Queens using J and brute force all permutations.
randomboard =: 3 : '? (y,y) $ y'
testsolution =: 4 : 0 NB. solution is a list of columns.
m =. x
n =. #x
solution =. y A. i. n
regions =. ({&m) <"1 (i. n) ,. solution
distinctregions =. n -: # ~. regions
adjacentregions =. 1 e. |2-/\solution
distinctregions * -. adjacentregions
)
findsolution =:3 : 0
board =: y
ns =. 1 i.~ (board & testsolution)"0 i. !#y
if. (ns = !#y) do. 'No solution found'
else.
echo 'Solution index is ', ": ns
ns A. i. #y end.
)
regions =: 4 : 0
({&x) <"1 (i. #x) ,. y
)
number2solution =: 4 : 0
y A. i. #x
)
writesolution =: 4 : 0
board =. x
sol =.y
m1 =. m
n1 =. #x
count =. 0
for_a. sol do.
m1 =. n1 (< count , a) } m1
count =. count + 1
end.
m1
)
writewithsolution=: 4 : 0
m1 =: x writesolution y
(":"1 x) ,. '|' ,. ":"1 m1
)
m =: randomboard 9
echo m writewithsolution findsolution m