1
0
Fork 0

Day 23: Complete refactor, with Part 2 complete.

This commit is contained in:
Jonathan Chan 2020-12-23 03:14:41 -08:00 committed by Jonathan Chan
parent d3e84fa8d0
commit 0ae16b5856
1 changed files with 47 additions and 26 deletions

View File

@ -4,36 +4,57 @@
(define input '(3 6 2 9 8 1 7 5 4)) (define input '(3 6 2 9 8 1 7 5 4))
(define (succ idx) (define CUPS 1000000)
(modulo (add1 idx) 9)) (define MOVES 10000000)
(define (add1* c) (define cups
(if (= c 9) 1 (add1 c))) (build-vector
(add1 CUPS)
#{cond
[(or (= % 0) (= % CUPS)) (first input)]
[(<= % (length input))
(let ([i (index-of input %)])
(if (< i (sub1 (length input)))
(list-ref input (add1 i))
(add1 (length input))))]
[(< % CUPS) (add1 %)]}))
(define (sub1* c) (define (play cup [cups cups] [CUPS CUPS])
(if (= c 1) 9 (sub1 c))) (define (prev cup)
(if (= cup 1) CUPS (sub1 cup)))
(define (play current cups moves stop) (let* ([one (vector-ref cups cup)]
(if (= moves stop) [two (vector-ref cups one)]
cups [three (vector-ref cups two)]
(let* ([curr-idx (index-of cups current)] [four (vector-ref cups three)]
[picked-up (list (list-ref cups (succ curr-idx)) [dest (let loop ([dest (prev cup)])
(list-ref cups (succ (succ curr-idx))) (if (or (= dest one) (= dest two) (= dest three))
(list-ref cups (succ (succ (succ curr-idx)))))] (loop (prev dest))
[dest-idx (let loop ([c (sub1* current)]) dest))]
(if (member c picked-up) [next (vector-ref cups dest)])
(loop (sub1* c)) (vector-set! cups cup four)
(index-of cups c)))]) (vector-set! cups three next)
(define-values (front back) (split-at cups (+ dest-idx 1))) (vector-set! cups dest one)
(let ([cups (append (remove* picked-up front) picked-up (remove* picked-up back))]) (vector-ref cups cup)))
(play (list-ref cups (succ (index-of cups current))) cups (add1 moves) stop)))))
(define part1 (define part1
(let* ([cups (play (first input) input 0 100)] (let ([cups (vector 0 7 9 6 3 4 2 5 1 8)])
[i (index-of cups 1)] (let loop ([cup (first input)]
[labels (append (drop cups (succ i)) (take cups i))]) [moves 0])
(apply string-append (map number->string labels)))) (if (= moves 100)
(let loop ([result '()] [cup 1])
(define next (vector-ref cups cup))
(if (= next 1)
(apply string-append (map number->string (reverse result)))
(loop (cons next result) next)))
(loop (play cup cups (length input)) (add1 moves))))))
(define part2 #f) (define part2
(let loop ([cup (first input)]
[moves 0])
(if (= moves MOVES)
(let* ([one (vector-ref cups 1)]
[two (vector-ref cups one)])
(* one two))
(loop (play cup) (add1 moves)))))
(show-solution part1 part2) (show-solution part1 part2)