This nqueens solution tries all ^~n possibilities by placing queens rank by rank, filtering out impossible solutions as it goes, and finally converting layouts to anagram index. Performance is far superior to filtering all !n full layouts as it solves n=12 in half minute (on this computer). I imagine the recursive algorithm tries only !n layouts filtering each step. The code is longer than others, but it's my entry and I understand it.

$ ijconsole

   identity =: =@:i.
   test =: (1 = >./)@:(+/ , +/"1 , +//. , +//.@:|.)
nqueens =: 3 :'A.@:((identity y)&i."2) (#~ test"_1)@:(,/)@:((identity y) ,"1 2/ ])^:y (1 0 0$y)'

   nqueens 5
10 13 36 44 50 69 75 83 106 109
   #nqueens 8
92
   timespacex 'smoutput # nqueens 12'
14200
14200
26.1923 1.14506e9

   timespacex '# nqueens 12'
26.1723 1.14506e9

conversions to anagram index with similar performance, shorter than identity&i:"2 are

to_anagram_index2 =: [:A.2^.#. NB. reversed, which won't matter for nqueens problem.
   to_anagram_index1 =: [:A.i.&1"1

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to