|
| 1 | +#lang racket |
| 2 | + |
| 3 | +(provide measure) |
| 4 | + |
| 5 | +(define (validate bucketOne bucketTwo goal) |
| 6 | + (if (> goal (max bucketOne bucketTwo)) |
| 7 | + (error "goal too big") |
| 8 | + (let ([g (gcd bucketOne bucketTwo)]) |
| 9 | + (if (not (zero? (remainder goal g))) |
| 10 | + (error "goal not reachable") |
| 11 | + null)))) |
| 12 | + |
| 13 | +(define (initial-contents bucketOne bucketTwo startBucket) |
| 14 | + (let ([one-full (cons bucketOne 0)] |
| 15 | + [two-full (cons 0 bucketTwo)]) |
| 16 | + (cond [(eq? startBucket 'one) |
| 17 | + (values one-full two-full)] |
| 18 | + [(eq? startBucket 'two) |
| 19 | + (values two-full one-full)] |
| 20 | + [else (error "invalid start bucket")]))) |
| 21 | + |
| 22 | +(define (move-from contents bucketOne bucketTwo) |
| 23 | + (let* ([a (car contents)] |
| 24 | + [b (cdr contents)] |
| 25 | + [a-to-b (min a (- bucketTwo b))] |
| 26 | + [b-to-a (min b (- bucketOne a))]) |
| 27 | + (remove-duplicates |
| 28 | + (list (cons 0 b) (cons a 0) |
| 29 | + (cons bucketOne b) (cons a bucketTwo) |
| 30 | + (cons (- a a-to-b) (+ b a-to-b)) |
| 31 | + (cons (+ a b-to-a) (- b b-to-a)))))) |
| 32 | + |
| 33 | +(define (move-all queue bucketOne bucketTwo visited) |
| 34 | + (for ([contents queue]) |
| 35 | + (set-add! visited contents)) |
| 36 | + (filter-not (λ (c) (set-member? visited c)) |
| 37 | + (append-map (λ (c) (move-from c bucketOne bucketTwo)) queue))) |
| 38 | + |
| 39 | +(define (achieves goal queue) |
| 40 | + (for/first ([contents queue] |
| 41 | + #:when (or (= (car contents) goal) |
| 42 | + (= (cdr contents) goal))) |
| 43 | + contents)) |
| 44 | + |
| 45 | +(define (result moves goal contents) |
| 46 | + (if (= (car contents) goal) |
| 47 | + (list moves 'one (cdr contents)) |
| 48 | + (list moves 'two (car contents)))) |
| 49 | + |
| 50 | +(define (measure bucketOne bucketTwo goal startBucket) |
| 51 | + (validate bucketOne bucketTwo goal) |
| 52 | + (let-values ([(start illegal) |
| 53 | + (initial-contents bucketOne bucketTwo startBucket)]) |
| 54 | + (let ([visited (mutable-set illegal)]) |
| 55 | + (do ([moves 0 (add1 moves)] |
| 56 | + [queue (list start) (move-all queue bucketOne bucketTwo visited)] |
| 57 | + [winner #f (achieves goal queue)]) |
| 58 | + (winner (result moves goal winner)))))) |
0 commit comments