Advent of Code 2020 solutions in Racket, I guess
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.0 KiB

#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))
(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"))))