-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5.jl
86 lines (80 loc) · 1.73 KB
/
day5.jl
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
include("../parser.jl")
function readrules!(p::InputParser)
rules = Set{Tuple{Int,Int}}()
while true
u = readint!(p)
consume!(p, "|")
v = readint!(p)
push!(rules, (u, v))
consume!(p, "\n")
if consume!(p, "\n")
break
end
end
rules
end
function readline!(p::InputParser)
us = Vector{Int}()
while true
u = readint!(p)
push!(us, u)
if !consume!(p, ",")
consume!(p, "\n")
break
end
end
us
end
function checkrules(rules::Set{Tuple{Int,Int}}, us::Vector{Int})
for (i, x) in pairs(us)
for y in us[i+1:end]
if (y, x) ∈ rules
return false
end
end
end
true
end
function ensurerules!(rules::Set{Tuple{Int,Int}}, us::Vector{Int})
found = false
while true
changed = false
for i in eachindex(us)
for j in i+1:length(us)
x, y = us[i], us[j]
if (y, x) ∈ rules
found = changed = true
us[i], us[j] = us[j], us[i]
end
end
end
if !changed
break
end
end
found
end
function part1(input::String)
p = InputParser(input, 1)
rules = readrules!(p)
result = 0
while !isend(p)
us = readline!(p)
if checkrules(rules, us)
result += us[length(us)÷2+1]
end
end
result
end
function part2(input::String)
p = InputParser(input, 1)
rules = readrules!(p)
result = 0
while !isend(p)
us = readline!(p)
if ensurerules!(rules, us)
result += us[length(us)÷2+1]
end
end
result
end