d12 p2 (stuck)

master
Matthew Butterick 5 years ago
parent 06bee6e7f1
commit 92ab44f92a

@ -37,7 +37,7 @@
(update-pair-velocity! m0 m)) (update-pair-velocity! m0 m))
(loop ms)))) (loop ms))))
(define (step moons count) (define (step! moons [count 1])
(for ([i (in-range count)]) (for ([i (in-range count)])
(update-gravity! moons) (update-gravity! moons)
(for-each update-position! moons)) (for-each update-position! moons))
@ -50,14 +50,14 @@
(abs val)))))) (abs val))))))
(check-eq? (check-eq?
(total-energy (step (str->moons "<x=-1, y=0, z=2> (total-energy (step! (str->moons "<x=-1, y=0, z=2>
<x=2, y=-10, z=-7> <x=2, y=-10, z=-7>
<x=4, y=-8, z=8> <x=4, y=-8, z=8>
<x=3, y=5, z=-1>") 10)) <x=3, y=5, z=-1>") 10))
179) 179)
(check-eq? (check-eq?
(total-energy (step (str->moons "<x=-8, y=-10, z=0> (total-energy (step! (str->moons "<x=-8, y=-10, z=0>
<x=5, y=5, z=10> <x=5, y=5, z=10>
<x=2, y=-7, z=3> <x=2, y=-7, z=3>
<x=9, y=-8, z=-3>") 100)) <x=9, y=-8, z=-3>") 100))
@ -65,5 +65,40 @@
;; 1 ;; 1
(check-eq? (check-eq?
(total-energy (step (str->moons (file->string "12.rktd")) 1000)) (total-energy (step! (str->moons (file->string "12.rktd")) 1000))
9876) 9876)
;; 2
(define (shift-origin! moons pos)
(for ([moon (in-list moons)])
(set-$moon-pos! moon (map - ($moon-pos moon) pos))))
(define (period str)
(for*/list ([which-moon (list first second third fourth)]
[which-dim (list first second third)])
(define moons (str->moons str))
(shift-origin! moons ($moon-pos (which-moon moons)))
(let loop ([count 1])
(step! moons)
(if (and (= 0 (which-dim ($moon-pos (which-moon moons))))
(= 0 (which-dim ($moon-vel (which-moon moons)))))
count
(loop (add1 count))))))
(check-eq?
(apply lcm (period "<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>"))
2772)
(check-eq?
(apply lcm
(period "<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>"))
4686774924)