aoc2020/12.rkt

67 lines
1.8 KiB
Racket

#lang curly-fn racket
(require "scripts/aoc.rkt")
;; solution for day 12
;; helper functions here
(define (d->r deg)
(* (/ deg 180) pi))
(define (part1 input)
(define-values [dir x y]
(for/fold ([dir 0] [x 0] [y 0]) ([ins (in-list input)])
(match-define (cons ltr num) ins)
(match ltr
["N" (values dir x (+ y num))]
["S" (values dir x (- y num))]
["E" (values dir (+ x num) y)]
["W" (values dir (- x num) y)]
["L" (values (+ dir (d->r num)) x y)]
["R" (values (- dir (d->r num)) x y)]
["F" (values dir (+ x (* num (cos dir))) (+ y (* num (sin dir))))])))
(inexact->exact (floor (+ (abs x) (abs y)))))
(define (part2 input)
(define (rot x y d)
(values
(- (* x (cos d)) (* y (sin d)))
(+ (* x (sin d)) (* y (cos d)))))
(define-values [sx sy wx wy]
(for/fold ([sx 0] [sy 0] [wx 10] [wy 1]) ([ins (in-list input)])
(match-define (cons ltr num) ins)
(match ltr
["N" (values sx sy wx (+ wy num))]
["S" (values sx sy wx (- wy num))]
["E" (values sx sy (+ wx num) wy)]
["W" (values sx sy (- wx num) wy)]
["L"
(define-values [nwx nwy] (rot wx wy (d->r num)))
(values sx sy nwx nwy)]
["R"
(define-values [nwx nwy] (rot wx wy (d->r (- num))))
(values sx sy nwx nwy)]
["F"
(values (+ sx (* num wx)) (+ sy (* num wy)) wx wy)])))
(inexact->exact (floor (+ (abs sx) (abs sy)))))
(module+ test
(require rackunit)
;; tests here
(displayln "no tests :("))
(module+ main
(define input
(for/list ([line (in-list (file->lines "inputs/12"))])
(match line
[(pregexp #px"^(.)([0-9]+)$" (list _ dir (app string->number num)))
(cons dir num)])))
;; part 1
(answer 12 1 (part1 input))
;; part 2
(answer 12 2 (part2 input))
(displayln "meow"))