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.

77 lines
2.4 KiB

#lang racket
(require "lib/common.rkt"
graph)
(define (next-adapter-step lst num step)
(for/first ([v (in-list lst)]
#:when (or (= v (+ step num))))
(cons step v)))
(define (next-adapter lst num)
(or (next-adapter-step lst num 1)
(next-adapter-step lst num 3)))
(define (day10a input)
(define (day10a/iter input [jolt 0])
(cond [(empty? input) '()]
[else
(define next (next-adapter input jolt))
(if next
(cons next (day10a/iter (rest input) (cdr next)))
empty)]))
(define res (day10a/iter input))
(* (count (lambda (v) (= (car v) 1)) res)
(add1 (count (lambda (v) (= (car v) 3)) res)))) ; why
(define (generate-edges input)
(define (next-adapter-edge lst jolt step)
(define val (next-adapter-step lst jolt step))
(if val (list (list jolt (cdr val))) '()))
(define adj-in (cons 0 input))
(for/fold ([edges '()]
[lst adj-in]
#:result edges)
([jolt (in-list adj-in)])
(values (append edges
(next-adapter-edge lst jolt 1)
(next-adapter-edge lst jolt 2)
(next-adapter-edge lst jolt 3))
(if (empty? lst) '() (rest lst)))))
(define (day10b input)
(define wanted (last input))
(define G (unweighted-graph/directed (generate-edges input)))
(define-vertex-property G n-paths #:init 0)
(n-paths-set! wanted 1)
(define (increment $from $to)
(when $from
(n-paths-set! $from
(+ (n-paths $from)
(n-paths $to)))))
(do-dfs G
#:order (lambda (_) (list 0))
#:process-unvisited?: #t
#:process-unvisited: (increment $from $to)
#:epilogue: (increment $from $to))
(hash-ref (n-paths->hash) 0))
(module+ main
(call-with-input-file "data/day10.txt"
(lambda (prt)
(define input (sort (map string->number (port->lines prt)) <))
(answer 10 1 (time (day10a input)))
(answer 10 2 (time (day10b input))))))
(module+ test
(require rackunit)
(call-with-input-file "data/day10.smalltest.txt"
(lambda (prt)
(define input (sort (map string->number (port->lines prt)) <))
(check-equal? (day10b input) 8)))
(call-with-input-file "data/day10.test.txt"
(lambda (prt)
(define input (sort (map string->number (port->lines prt)) <))
(check-equal? (day10a input) (* 22 10))
(check-equal? (day10b input) 19208))))