From 8b17fe1d26447f0f0f0cf9c65493161a0b6da807 Mon Sep 17 00:00:00 2001 From: haskal Date: Tue, 15 Dec 2020 00:27:14 -0500 Subject: [PATCH] day 15: improve solution spaghettiness somewhat --- 15.rkt | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/15.rkt b/15.rkt index 544ac8f..6705ebb 100644 --- a/15.rkt +++ b/15.rkt @@ -6,20 +6,21 @@ (define (naive-solution input limit) (define seen-numbers (make-hash)) - (define prev #f) - (for ([num (in-list input)] [i (in-naturals)]) - (hash-set! seen-numbers num i) - (set! prev num)) + (define prev + (for/last ([num (in-list input)] [i (in-naturals)]) + (hash-set! seen-numbers num i) + num)) + ;; delay "seeing" numbers by one iteration (hash-remove! seen-numbers prev) - (for ([i (in-range (length input) limit)]) + (for/fold ([prev prev]) ([i (in-range (length input) limit)]) (define new-val - (cond - [(hash-has-key? seen-numbers prev) (sub1 (- i (hash-ref seen-numbers prev)))] - [else 0])) + (match (hash-ref seen-numbers prev #f) + [#f 0] + [idx (- i 1 idx)])) + ;; _now_ we've "seen" it, but it happened on the last turn (hash-set! seen-numbers prev (sub1 i)) - (set! prev new-val)) - prev) + new-val)) (define part1 #{naive-solution % 2020}) (define part2 #{naive-solution % 30000000})