1
0
Fork 0

Refactored Day 15: Using vector instead of hash.

This commit is contained in:
Jonathan Chan 2020-12-14 22:03:26 -08:00 committed by Jonathan Chan
parent 4a858eca81
commit 9c9511a05b
1 changed files with 9 additions and 7 deletions

View File

@ -5,17 +5,19 @@
(define input '(5 1 9 18 13 8 0))
(define (play end)
(define turns
(make-hash (map cons input (range 1 (add1 (length input))))))
(let loop ([turn (length input)] [curr (last input)])
(define turns (make-vector end #f))
(for-each #{vector-set! turns %1 (add1 %2)}
input (range (length input)))
(let loop ([turn (length input)]
[curr (last input)])
(cond
[(>= turn end) curr]
[(hash-has-key? turns curr)
(let ([next (- turn (hash-ref turns curr))])
(hash-set! turns curr turn)
[(vector-ref turns curr)
(let ([next (- turn (vector-ref turns curr))])
(vector-set! turns curr turn)
(loop (add1 turn) next))]
[else
(hash-set! turns curr turn)
(vector-set! turns curr turn)
(loop (add1 turn) 0)])))
(show-solution (play 2020) (play 30000000))