-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.fnl
66 lines (57 loc) · 1.97 KB
/
day3.fnl
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
(local input-file :./inputs/day3.txt)
(fn str-to-set [str]
(let [s {}]
(str:gsub "." #(tset s $1 true))
s))
(fn get-priority [c]
(let [b (c:byte)]
(if (>= b 97) (- b 96) (-> b (- 65) (+ 27)))))
(fn part-1 []
(fn split-sack [sack]
(let [half (/ (length sack) 2)]
(values (sack:sub 1 half) (sack:sub (+ half 1)))))
(with-open [f (io.open input-file :r)]
(->> (accumulate [total 0 sack (f:lines)]
(let [(fstr bstr) (split-sack sack)
front (str-to-set fstr)
back (str-to-set bstr)]
(-> (accumulate [char "" fc _ (pairs front)]
(if (. back fc) fc char))
(get-priority)
(+ total))))
(print "Part 1:"))))
(fn part-2 []
(fn read-n-lines [get-next-line i n groupped]
"get the next n lines, return nil if no lines left"
(if (> i n)
groupped
(let [line (get-next-line)]
(if (not= nil line)
(do
(table.insert groupped line)
(read-n-lines get-next-line (+ 1 i) n groupped))
nil))))
(fn str-arr-to-set-arr [arr]
"transform array of strings to array of sets"
(accumulate [set-arr [] _ val (ipairs arr)]
(do
(table.insert set-arr (str-to-set val))
set-arr)))
(fn get-total [total get-group]
(let [group (get-group)]
(if (= group nil) total
(do
;; find commonality in sets
(-> (let [group (str-arr-to-set-arr group)]
(accumulate [local-total 0 char _ (pairs (. group 1))]
(if (and (. group 2 char) (. group 3 char))
(get-priority char)
local-total)))
(+ total)
(get-total get-group))))))
(with-open [f (io.open input-file :r)]
(let [get-next-line #(f:read :*l)]
(->> (get-total 0 #(read-n-lines get-next-line 1 3 []))
(print "Part 2:")))))
(part-1)
(part-2)