my attempt to do the exercises in sicp.

Saturday, July 19, 2008

sicp exercise 2.42



; Exercise 2.42. 



; Figure:  A solution to the eight-queens puzzle.

; The ``eight-queens puzzle'' asks how to place eight queens on a chessboard so that no queen is in check from any other (i.e., no two queens are in the same row, column, or diagonal). One possible solution is shown in figure 2.8. One way to solve the puzzle is to work across the board, placing a queen in each column. Once we have placed k - 1 queens, we must place the kth queen in a position where it does not check any of the queens already on the board. We can formulate this approach recursively: Assume that we have already generated the sequence of all possible ways to place k - 1 queens in the first k - 1 columns of the board. For each of these ways, generate an extended set of positions by placing a queen in each row of the kth column. Now filter these, keeping only the positions for which the queen in the kth column is safe with respect to the other queens. This produces the sequence of all ways to place k queens in the first k columns. By continuing this process, we will produce not only one solution, but all solutions to the puzzle.

; We implement this solution as a procedure queens, which returns a sequence of all solutions to the problem of placing n queens on an n× n chessboard. Queens has an internal procedure queen-cols that returns the sequence of all ways to place queens in the first k columns of the board.

; (define (queens board-size)
;   (define (queen-cols k) 
;     (if (= k 0)
;         (list empty-board)
;         (filter
;          (lambda (positions) (safe? k positions))
;          (flatmap
;           (lambda (rest-of-queens)
;             (map (lambda (new-row)
;                    (adjoin-position new-row k rest-of-queens))
;                  (enumerate-interval 1 board-size)))
;           (queen-cols (- k 1))))))
;   (queen-cols board-size))

; In this procedure rest-of-queens is a way to place k - 1 queens in the first k - 1 columns, and new-row is a proposed row in which to place the queen for the kth column. Complete the program by implementing the representation for sets of board positions, including the procedure adjoin-position, which adjoins a new row-column position to a set of positions, and empty-board, which represents an empty set of positions. You must also write the procedure safe?, which determines for a set of positions, whether the queen in the kth column is safe with respect to the others. (Note that we need only check whether the new queen is safe -- the other queens are already guaranteed safe with respect to each other.)




(define (enumerate-interval start end)
  (cond ((> start end) (list))
        (else (cons start (enumerate-interval (+ start 1) end)))))

(define (accumulate proc nil-val seq)
  (cond ((null? seq) nil-val)
        (else (proc (car seq) (accumulate proc nil-val (cdr seq))))))

; this is a map that applies proc depending on index. it provides index to proc. proc takes 2 arguments can this map-with-index be written in terms of simple map?
(define (mapi proc seq)
  (define (iter index items)
    (cond ((null? items) (list))
          (else (cons (proc index (car items)) (iter (+ index 1) (cdr items))))))
  (iter 1 seq))

; similarily a filter procedure which also provides index to predicate
(define (filteri pred seq)
  (define (iter index items)
    (cond ((null? items) (list))
          ((pred index (car items)) (cons (car items) (iter (+ index 1) (cdr items))))
          (else (iter (+ index 1) (cdr items)))))
  (iter 1 seq))

(define (for-each proc seq)
  (cond ((null? seq) 0)
        (else (proc (car seq)) (for-each proc (cdr seq)))))

(define (flatmap proc seq)
  (accumulate append (list) (map proc seq)))

(define (queens board-size)
  (define (queen-cols k) 
    (if (= k 0)
        (list empty-board)
        (filter
          (lambda (positions) (safe? k positions))
          (flatmap
            (lambda (rest-of-queens)
              (map (lambda (new-row)
                     (adjoin-position new-row k rest-of-queens))
                   (enumerate-interval 1 board-size)))
            (queen-cols (- k 1))))))
  (queen-cols board-size))

(define empty-board (list))

(define (adjoin-position row col queens)
  (append (list row) queens))

(define (safe? k positions)
  (define queen (car positions))
  (define (check-mate col row)
    (or (= queen row) (= col (abs (- row queen)))))
  (null? (filteri check-mate (cdr positions))))

(define (print-board board)
  (define max (length board))
  (define (print-row col)
    (define (iter row)
      (cond ((= row col) (display "q ") (iter (+ row 1)))
            ((> row max) (newline))
        (else (display ". ") (iter (+ row 1)))))
    (iter 1))
  (for-each print-row board)
  (display "------------------")
  (newline))

(for-each print-board (queens 7)) (newline)



2 comments:

weima said...

increase the stack size for board of more than 8.

use the following to increase the stack size in guile.

(debug-set! stack 999999)

Unknown said...

Recently I'm also working on this problem. I find your safe? function is different from mine. My check-mate is like this:

(define (check-mate col row)
(or (= queen row)
(= (+ k queen) (+ col row)
(= (- k queen) (- col row)))

This will ensure queens are in different rows and diagonals.