Implement till 2.50 and visualize picture language via pil
This commit is contained in:
@@ -219,9 +219,73 @@
|
||||
|
||||
(display (unique-sum-triples 6 10)) (newline)
|
||||
|
||||
(display "\nex-2.42\n")
|
||||
(display "\nex-2.42 - eight queens\n")
|
||||
|
||||
; Creates a new list with numbers [1..n] cons'd to the current lists
|
||||
(define (add-numbers n xs)
|
||||
(flatmap
|
||||
(lambda (x) (map (lambda (i) (cons i x)) (enumerate-interval 1 n)))
|
||||
xs))
|
||||
|
||||
; Checks if the first queen on the board is safe relative to the other queens
|
||||
(define (safe? board)
|
||||
(define (valid-position row diag board)
|
||||
(if (null? board)
|
||||
#t
|
||||
(let ((cur_row (car board)))
|
||||
(if (or (= row cur_row) ; same row
|
||||
(= (+ row diag) cur_row) ; upper right diagonal
|
||||
(= (- row diag) cur_row)) ; lower left diagonal
|
||||
#f
|
||||
(valid-position row (+ diag 1) (cdr board))))))
|
||||
(valid-position (car board) 1 (cdr board)))
|
||||
|
||||
(define empty-board (list nil))
|
||||
|
||||
(define (queens n)
|
||||
(define (queens-cols k)
|
||||
(if (= k 0)
|
||||
empty-board
|
||||
(filter safe? (add-numbers n (queens-cols (- k 1))))))
|
||||
(queens-cols n))
|
||||
|
||||
(display (length (queens 8))) (newline)
|
||||
|
||||
; Till here was my own implementation for practice.
|
||||
; Here is the official solution:
|
||||
|
||||
(define (adjoin-position new-row k rest-of-queens)
|
||||
(cons new-row rest-of-queens))
|
||||
|
||||
(define (queens board-size)
|
||||
(define empty-board nil)
|
||||
(define (queen-cols k)
|
||||
(if (= k 0)
|
||||
(list empty-board)
|
||||
(filter
|
||||
(lambda (positions) (safe? positions)) ; removed k because we don't need it
|
||||
(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))
|
||||
|
||||
(display (length (queens 8))) (newline)
|
||||
|
||||
|
||||
(display "\nex-2.43\n")
|
||||
|
||||
(display "\nex-2.43 - see comments\n")
|
||||
;(flatmap
|
||||
; (lambda (new-row)
|
||||
; (map (lambda (rest-of-queens)
|
||||
; (adjoin-position new-row k rest-of-queens))
|
||||
; (queen-cols (- k 1))))
|
||||
; (enumerate-interval 1 board-size))
|
||||
|
||||
; Louis' implementation computes the queens for the remaining columns
|
||||
; board-size times for each column. That means for two columns the program is
|
||||
; two times slower. For three, two times times three times, in other words, the
|
||||
; execution time is (board-size! * T).
|
||||
|
||||
|
||||
Reference in New Issue
Block a user