-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.carth
37 lines (32 loc) · 1.09 KB
/
day2.carth
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(import std)
(define main
(do io/bind
(<- inp (io/map unwrap! (read-file "inputs/day2.txt")))
(let1 cmds (map parse-cmd (lines inp)))
(display "Part 1:")
(display (show-int (let1 [x y] (exec1 cmds)
(* x y))))
(display "Part 2:")
(display (show-int (let1 [x y _aim] (exec2 cmds)
(* x y))))))
(data Cmd (Forward Int) (Down Int))
(define (parse-cmd line)
(let ((ss (words line))
([s1 ss] (unwrap! (next ss)))
([s2 _] (unwrap! (next ss)))
(val (unwrap! (parse-int s2))))
(match s1
(case "forward" (Forward val))
(case "down" (Down val))
(case "up" (Down (neg val)))
(case _ (panic "unreachable")))))
(define (exec1 cmds)
(define (go [x y])
(fmatch (case (Forward dx) [(+ dx x) y])
(case (Down dy) [x (+ dy y)])))
(foldl go [0 0] cmds))
(define (exec2 cmds)
(define (go [x y aim])
(fmatch (case (Forward dx) [(+ dx x) (+ (* dx aim) y) aim])
(case (Down daim) [x y (+ daim aim)])))
(foldl go [0 0 0] cmds))