Feeds:
Posts
Comments

## Displaying N-Queens solutions

Hopefully some of you have tried out the AIMA code for constraint satisfaction problems. If you are looking at the N-Queens problem, here is some code that will display the solution for you. To use it, just pass it the result value of the CSP search. For example:

`CL-USER 49 > (csp-forward-checking-search (make-nqueens-problem :n 8))`
`#<NODE f(8) = g(8) + h(0) state:#<CSP ((7 (4) 4 NIL) (6 (6) 6 NIL) (5 (1) 1 NIL) (4 (4 5) 5 NIL) (3 (2 6) 2 NIL) (2 (0 1 6) 0 NIL) (1 (0 1 2 3 4 5) 3 NIL) (0 (0 1 2 3 4 5 6 7) 7 NIL))>>`
`CL-USER 50 > (display-nqueens-solution *)`
` - - - - Q - - -`
` - - - - - - Q -`
` - Q - - - - - -`
` - - - - - Q - -`
` - - Q - - - - -`
` Q - - - - - - -`
` - - - Q - - - -`
` - - - - - - - Q`
`NIL`

Code after the jump:

`(defun display-nqueens-state (state)`
`  "Display the solution state (for a state with complete assignments."`
`  (let* ((vars (csp-state-assigned state))`
`         (n (length vars)))`
`    ;; Iterate through the vars (rows), printing each.`
`    (dolist (Var vars)`
`      (let ((q-pos (csp-var-value var)))`
`        (terpri)`
`        (dotimes (x n)`
`          (if (= x q-pos)`
`              (princ " Q")`
`            (princ " -")))))`
`    (terpri)))`
`(defun display-nqueens-solution (solution-node)`
`  "Call this on the returned value for the CSP search functions to display`
`   the solution."`
`  (display-nqueens-state (node-state solution-node)))`
Advertisements