-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday02.clj
70 lines (53 loc) · 1.51 KB
/
day02.clj
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
(ns day02
(:require aoc))
(def keypad-1 [[1 2 3]
[4 5 6]
[7 8 9]])
(def keypad-2 [[0 0 1 0 0]
[0 2 3 4 0]
[5 6 7 8 9]
[0 \A \B \C 0]
[0 0 \D 0 0]])
(defn coord->key [keypad [dx dy] [x y]]
((keypad (+ y dy)) (+ x dx)))
(defn move [[x y] dir]
(case dir
:left [(dec x) y]
:right [(inc x) y]
:up [x (dec y)]
:down [x (inc y)]))
(defn p1-inbounds? [[x y]]
(and (< (abs x) 2)
(< (abs y) 2)))
(defn p2-inbounds? [[x y]]
(<= (+ (abs x) (abs y)) 2))
(defn press [pos instruction in-keypad?]
(reduce
(fn [pos instr]
(let [new-pos (move pos instr)]
(if (in-keypad? new-pos) new-pos pos)))
pos
instruction))
(defn type-password [instructions part]
(let [{:keys [keypad valid? start offset]}
(case part
1 {:keypad keypad-1 :valid? p1-inbounds? :start [0 0] :offset [1 1]}
2 {:keypad keypad-2 :valid? p2-inbounds? :start [-2 0] :offset [2 2]})]
(->> instructions
(reduce (fn [pressed-keys instr]
(conj pressed-keys (press (peek pressed-keys) instr valid?)))
[start])
rest
(map (partial coord->key keypad offset))
(apply str))))
(defn parse-line [line]
(map {\L :left
\R :right
\U :up
\D :down}
line))
(defn solve [input]
(let [instructions (aoc/read-input input parse-line)]
(for [part [1 2]]
(type-password instructions part))))
(solve 2)