diff --git a/9.rkt b/9.rkt index 34e5a23..498ec44 100644 --- a/9.rkt +++ b/9.rkt @@ -6,39 +6,38 @@ ;; helper functions here -(define (part1 input) - (define vec (list->vector input)) - (let/ec exit - (for ([i (in-range 25 (vector-length vec))]) - (define valid? - (for*/first ([a (in-range (- i 25) i)] [b (in-range a i)] - #:when (= (vector-ref vec i) (+ (vector-ref vec a) (vector-ref vec b)))) #t)) - (unless valid? - (exit (vector-ref vec i)))))) +;; linear time sum checker, assuming sorted subrange +(define (contains-sum? vec start end wanted-sum) + (define (helper [a start] [b (sub1 end)]) + (define cur-sum (+ (vector-ref vec a) (vector-ref vec b))) + (cond + [(>= a b) #f] + [(= cur-sum wanted-sum) #t] + [(< cur-sum wanted-sum) (helper (add1 a) b)] + [(> cur-sum wanted-sum) (helper a (sub1 b))])) + (vector-sort! vec < start end) + (helper)) -(define (part2 input) - (define pt1 10884537) - (define pt1-i 501) - (let/ec exit - (define vec (list->vector input)) - (define (cb args) - (when (= pt1 (apply + args)) - (exit (+ (apply min args) (apply max args))))) - (for* ([ct (in-range 3 100)] [i (in-range 0 (- pt1-i ct))]) - (define sub (vector-copy vec i (+ i ct))) - (cb (vector->list sub))))) +;; continuously sort the part of the vector below the iterator, and call contains-sum? +(define (part1 vec) + (for*/first ([i (in-range 25 (vector-length vec))] [x (in-value (vector-ref vec i))] + #:unless (contains-sum? vec 0 i x)) + (cons i x))) -(module+ test - (require rackunit) - ;; tests here - (displayln "no tests :(")) +(define (part2 vec pt1-ans) + (match-define (cons pt1-i pt1-val) pt1-ans) + (for*/first ([ct (in-range 3 100)] [i (in-range 0 (- pt1-i ct))] + [sub (in-value (vector-copy vec i (+ i ct)))] + #:when (= pt1-val (for/fold ([x 0]) ([v (in-vector sub)]) (+ x v)))) + (+ (vector-argmin identity sub) (vector-argmax identity sub)))) (module+ main - (define input (file->list "inputs/9")) + (define input (list->vector (file->list "inputs/9"))) ;; part 1 - (answer 9 1 (part1 input)) + (define pt1 (part1 (vector-copy input))) + (answer 9 1 (cdr pt1)) ;; part 2 - (answer 9 2 (part2 input)) + (answer 9 2 (part2 (vector-copy input) pt1)) (displayln "meow"))