|
355 | 355 | (define (require p) (if (not p) (amb)))
|
356 | 356 | (define (eight-queens)
|
357 | 357 | (define (ok-position? columns rows)
|
358 |
| - true) |
| 358 | + (define (this-ok? c r cs rs) |
| 359 | + (define (attacks? x1 y1 x2 y2) |
| 360 | + (cond ((= x1 x2) true) |
| 361 | + ((= y1 y2) true) |
| 362 | + ((= (abs (- x1 x2)) (abs (- y1 y2))) true) |
| 363 | + (else false))) |
| 364 | + (if (null? cs) |
| 365 | + true |
| 366 | + (if (attacks? c r (car cs) (car rs)) |
| 367 | + false |
| 368 | + (this-ok? c r (cdr cs) (cdr rs))))) |
| 369 | + (if (null? columns) |
| 370 | + true |
| 371 | + (let ((rest-columns (cdr columns)) |
| 372 | + (rest-rows (cdr rows))) |
| 373 | + (if (not (ok-position? rest-columns rest-rows)) |
| 374 | + false |
| 375 | + (let ((this-column (car columns)) |
| 376 | + (this-row (car rows))) |
| 377 | + (this-ok? this-column this-row rest-columns rest-rows)))))) |
359 | 378 | (let ((q1 (amb 1 2 3 4 5 6 7 8))
|
360 | 379 | (q2 (amb 1 2 3 4 5 6 7 8))
|
361 | 380 | (q3 (amb 1 2 3 4 5 6 7 8))
|
|
368 | 387 | (rows (list 1 2 3 4 5 6 7 8)))
|
369 | 388 | (require (ok-position? columns rows))
|
370 | 389 | (list q1 q2 q3 q4 q5 q6 q7 q8))))
|
| 390 | + |
| 391 | +(define (ok-position? columns rows) |
| 392 | + (define (this-ok? c r cs rs) |
| 393 | + (define (attacks? x1 y1 x2 y2) |
| 394 | + (cond ((= x1 x2) true) |
| 395 | + ((= y1 y2) true) |
| 396 | + ((= (abs (- x1 x2)) (abs (- y1 y2))) true) |
| 397 | + (else false))) |
| 398 | + (if (null? cs) |
| 399 | + true |
| 400 | + (if (attacks? c r (car cs) (car rs)) |
| 401 | + false |
| 402 | + (this-ok? c r (cdr cs) (cdr rs))))) |
| 403 | + (if (null? columns) |
| 404 | + true |
| 405 | + (let ((rest-columns (cdr columns)) |
| 406 | + (rest-rows (cdr rows))) |
| 407 | + (if (not (ok-position? rest-columns rest-rows)) |
| 408 | + false |
| 409 | + (let ((this-column (car columns)) |
| 410 | + (this-row (car rows))) |
| 411 | + (this-ok? this-column this-row rest-columns rest-rows)))))) |
| 412 | + |
| 413 | +(ok-position? '(1 3) '(3 2)) |
| 414 | + |
0 commit comments