Browse Source

day 9

canon
Hazel Levine 8 months ago
parent
commit
f36bb7c5fe
Signed by: hazel GPG Key ID: 1884029A28789A62
  1. 1000
      data/day9.txt
  2. 60
      day9.rkt

1000
data/day9.txt
File diff suppressed because it is too large
View File

60
day9.rkt

@ -0,0 +1,60 @@
#lang racket
(require "lib/common.rkt")
(define (is-2sum? lst num)
(define sorted-list (sort lst <))
(define reversed-list (reverse sorted-list))
(define (is-2sum?/iter sorted reversed)
(cond [(or (empty? sorted)
(empty? reversed))
#f]
[else
(define sum (+ (first sorted)
(first reversed)))
(cond [(= sum num) #t]
[(> sum num)
(is-2sum?/iter sorted (rest reversed))]
[(< sum num)
(is-2sum?/iter (rest sorted) reversed)])]))
(is-2sum?/iter sorted-list reversed-list))
(define (day9a input n-take)
(define-values (initial-preamble initial-post) (split-at input n-take))
(define (day9a/iter preamble lst)
(cond [(empty? lst) (displayln preamble)]
[(is-2sum? preamble (first lst))
(day9a/iter (append (rest preamble) (list (first lst)))
(rest lst))]
[else (first lst)]))
(day9a/iter initial-preamble initial-post))
(define (day9b input n-take)
(define to-sum (day9a input n-take))
(let/ec leave
(define vec (list->vector input))
(define (sum? lst)
(when (= to-sum (apply + lst))
(leave (+ (apply min lst) (apply max lst)))))
(for* ([i (in-range 0 (vector-length vec))]
[j (in-range 0 (- (vector-length vec) i))]
#:when (< (vector-ref vec (+ i j)) to-sum))
(define sub (vector-copy vec i (+ i j)))
(sum? (vector->list sub)))))
(module+ main
(call-with-input-file "data/day9.txt"
(lambda (prt)
(define input (map string->number (port->lines prt)))
(answer 9 1 (day9a input 25))
(answer 9 2 (day9b input 25)))))
(module+ test
(require rackunit)
(call-with-input-file "data/day9.txt"
(lambda (prt)
(define input (map string->number (port->lines prt)))
(check-equal? (day9a input 25) 22477624
"final answer part 1")
(check-equal? (day9b input 25) 2980044
"final answer part 2"))))
Loading…
Cancel
Save