day 9: apply optimizations to part 1

This commit is contained in:
xenia 2020-12-09 00:54:22 -05:00
parent 7c2b008624
commit 4e2ea7d641
1 changed files with 26 additions and 27 deletions

53
9.rkt
View File

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