N-queens problem: Difference between revisions

→‎{{header|Python}}: Explanation copied.
(→‎{{header|Python}}: Explanation copied.)
Line 120:
== len(set(vec[i]-i for i in cols))):
print ( vec )</lang>
 
The output is presented in vector form (each number represents the column position of a queen on consecutive rows). The vector can be pretty printed by substituting a call to <code>board</code> instead of <code>print</code>, with the same argument, and where board is pre-defined as:
<lang python>def board(vec):
print ("\n".join('.' * i + 'Q' + '.' * (n-i-1) for i in vec) + "\n===\n")</lang>
 
Raymonds description is:
:With the solution represented as a vector with one queen in each row, we don't have to check to see if two queens are on the same row. By using a permutation generator, we know that no value in the vector is repeated, so we don't have to check to see if two queens are on the same column. Since rook moves don't need to be checked, we only need to check bishop moves.
 
:The technique for checking the diagonals is to add or subtract the column number from each entry, so any two entries on the same diagonal will have the same value (in other words, the sum or difference is unique for each diagnonal). Now all we have to do is make sure that the diagonals for each of the eight queens are distinct. So, we put them in a set (which eliminates duplicates) and check that the set length is eight (no duplicates were removed).
 
:Any permutation with non-overlapping diagonals is a solution. So, we print it and continue checking other permutations.
 
=={{header|Ruby}}==
Anonymous user