-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday05.lua
145 lines (120 loc) · 2.61 KB
/
day05.lua
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
local read_input = require('lib.read_input')
local str = require('lib.split_str')
local Day05 = {}
function Day05:new(o, input)
o = o or {}
o.parent = self
setmetatable(o, self)
self.__index = self
o.input = (input and input.input) or {}
return o
end
local Part1 = Day05:new()
function Part1:new(input)
local o = {}
Day05.new(self, o, input)
return o
end
function Day05:is_sorted(n, closures)
for i = 1, #n do
for j = i + 1, #n do
if closures[n[j]] and closures[n[j]][n[i]] then
return false
end
end
end
return true
end
function Day05:sorted(n, closures)
for i = 1, #n do
for j = i + 1, #n do
if closures[n[j]] and closures[n[j]][n[i]] then
n[j], n[i] = n[i], n[j]
end
end
end
end
function Part1:solve()
local sorted_count = 0
for _, n in pairs(self.input.numbers) do
if self:is_sorted(n, self.input.rules) then
sorted_count = sorted_count + n[math.floor((#n / 2) + 0.5)]
end
end
return sorted_count
end
local Part2 = Day05:new()
function Part2:new(input)
local o = {}
Day05.new(self, o, input)
return o
end
function Part2:solve()
local sorted_count = 0
for _, n in pairs(self.input.numbers) do
if not self:is_sorted(n, self.input.rules) then
self:sorted(n, self.input.rules)
sorted_count = sorted_count + n[math.floor((#n / 2) + 0.5)]
end
end
return sorted_count
end
local Input = {}
function Input:new(o)
o = o or {}
o.parent = self
setmetatable(o, self)
self.__index = self
local input = read_input("47|53\
97|13\
97|61\
97|47\
75|29\
61|13\
75|53\
29|13\
97|29\
53|29\
61|53\
97|53\
61|29\
47|13\
75|47\
97|75\
47|61\
75|61\
47|29\
75|13\
53|13\
\
75,47,61,53,29\
97,61,53,29,13\
75,29,13\
75,97,47,61,53\
61,13,29\
97,13,75,29,47\
") .. "\n"
local sections = str.global_match(input, "(.-)\n\n")
local rules = str.split(sections[1], "(.-)\n")
local rule_map = {}
for _, v in pairs(rules) do
local t = str.split(v, "|")
rule_map[t[1]] = rule_map[t[1]] or {}
rule_map[t[1]][t[2]] = true
end
local pages = str.split(sections[2], "(.-)\n")
local page_numbers = {}
for _, v in pairs(pages) do
table.insert(page_numbers, str.split(v, ","))
end
o.input = {
rules = rule_map,
numbers = page_numbers
}
return o
end
local input = Input:new()
local p1 = Part1:new(input)
print("Part 1: " .. p1:solve())
local p2 = Part2:new(input)
print("Part 2: " .. p2:solve())