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.

56 lines
1.8 KiB

#lang racket
(require "lib/common.rkt")
(define (day1a lst)
(define sorted-list (sort lst <))
(define reversed-list (reverse sorted-list))
(define (day1a/iter sorted reversed)
(cond [(or (empty? sorted)
(empty? reversed))
(error "oh no")]
[else
(define sum (+ (first sorted)
(first reversed)))
(cond [(= sum 2020)
(* (first sorted) (first reversed))]
[(> sum 2020)
(day1a/iter sorted (rest reversed))]
[(< sum 2020)
(day1a/iter (rest sorted) reversed)])]))
(day1a/iter sorted-list reversed-list))
(define (day1b lst)
(define (inner-report lst ht i)
(cond [(empty? lst) ht]
[else
(define j (first lst))
(define key (- 2020 i j))
(inner-report (rest lst)
(hash-set ht key (list i j key))
i)]))
(define (day1b/iter lst ht)
(define num (first lst))
(define new-hash (inner-report (rest lst) ht num))
(cond [(hash-has-key? new-hash num)
(apply * (hash-ref new-hash num))]
[else (day1b/iter (rest lst) new-hash)]))
(cond [(empty? lst) (error "oh no")]
[else (day1b/iter lst (make-immutable-hash))]))
(module+ main
(call-with-input-file "data/day1.txt"
(lambda (prt)
(define lines (map string->number (port->lines prt)))
(answer 1 1 (day1a lines))
(answer 1 2 (day1b lines)))))
(module+ test
(require rackunit)
(call-with-input-file "data/day1.txt"
(lambda (prt)
(define lines (map string->number (port->lines prt)))
(check-equal? (day1a lines) 542619
"final answer part 1")
(check-equal? (day1b lines) 32858450
"final answer part 2"))))