Sunday, June 7, 2009

Ex-2.42

;positions on the board are represented using pair
;(row col) where 1<=row,col<= board-size
(define empty-board '())
(define (adjoin-position row col rest-of-queens)
(cons (cons row col) rest-of-queens))
(define (safe? k positions)
;returns #t if a pos is safe with respect to other
;positions
(define (safe-position? pos positions)
(if (null? positions) true
(and (safe-two-positions? pos (car positions))
(safe-position? pos (cdr positions)))))

;returns #t if two positions are safe for each other
(define (safe-two-positions? pos1 pos2)
(cond
((= (car pos1) (car pos2)) #f)
((= (cdr pos1) (cdr pos2)) #f)
((same-diagonal? pos1 pos2) #f)
(else #t)))

;returns #t if two positions are on same diagonal
(define (same-diagonal? pos1 pos2)
(= (abs (- (car pos1) (car pos2)))
(abs (- (cdr pos1) (cdr pos2)))))

;here we made the assumption that first position
;in given positions is the one which has queen
;on k'th column, this holds true because of the
;way code written in procedure queens, this is
;not really right assumption to make but then we
;can change that anytime.
(safe-position? (car positions) (cdr positions)))

No comments:

Post a Comment