Guest User

Untitled

a guest
Feb 21st, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. (require (only-in "../lib.ss" enumerate-interval flatmap nil))
  2.  
  3. ; checks not horiz
  4. (define (safe? k queens)
  5. (define (problem-horiz? k-queen-row queens num-at)
  6. (cond ((eq? queens nil) #f) ; we've tried them all
  7. ((= k num-at) #f) ; this is comparing against itself
  8. ((= k-queen-row (car queens)) #t) ; the row of current queen is the same as kth queen
  9. (else (problem-horiz? k-queen-row (cdr queens) (+ 1 num-at)))))
  10. (define (problem-diag? k-row k-col queens num-at)
  11. ;(display k-row) (display " ") (display k-col) (display queens) (display num-at) (display "\n")
  12. (let ((queen-top-diag-at-k (+ (car queens) (- k-col num-at)))
  13. (queen-bot-diag-at-k (- (car queens) (- k-col num-at))))
  14. ; (display queen-top-diag-at-k) (display " ") (display queen-bot-diag-at-k) (display "\n")
  15. (cond ((eq? queens nil) #f) ; we've tried them all
  16. ((= k num-at) #f) ; this is comparing against itself, thus tried all previous
  17. ((or (= k-row queen-top-diag-at-k)
  18. (= k-row queen-bot-diag-at-k)) #t)
  19. (else (problem-diag? k-row k-col (cdr queens) (+ 1 num-at))))))
  20. (and (not (problem-horiz? (list-ref queens (- k 1)) queens 1))
  21. (not (problem-diag? (list-ref queens (- k 1)) k queens 1))))
  22.  
  23. (define (adjoin-position row col rest-of-queens)
  24. (append rest-of-queens (list row))) ; cheats a little bit, given that the col is implicit to the ordering
  25.  
  26. (define (queens board-size)
  27. (define empty-board '())
  28. (define (queen-cols k)
  29. (if (= k 0)
  30. (list empty-board)
  31. (filter
  32. (lambda (positions) (safe? k positions))
  33. (flatmap ; all second lists within the main list, flatten
  34. (lambda (rest-of-queens) ; for each possibility
  35. (map (lambda (new-row) ; for each new row
  36. (adjoin-position new-row k rest-of-queens)) ;add this row to each possibility
  37. (enumerate-interval 1 board-size)))
  38. (queen-cols (- k 1)))))) ; this is all possibilities
  39. (queen-cols board-size))
  40.  
  41. (queens 8 )
Add Comment
Please, Sign In to add comment