-
Notifications
You must be signed in to change notification settings - Fork 0
/
13.jl
77 lines (71 loc) · 1.95 KB
/
13.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
"""
Day 13: Distress Signal
https://adventofcode.com/2022/day/13
"""
function is_right_order(a, b)
for (left, right) in zip(a, b)
if left isa Int && right isa Int
if left == right
continue
elseif left > right
return false
else
return true
end
elseif left isa Vector && right isa Vector
result = is_right_order(left, right)
if isnothing(result)
continue
else
return(result)
end
else
if left isa Int
result = is_right_order([left], right)
else
result = is_right_order(left, [right])
end
if isnothing(result)
continue
else
return(result)
end
end
end
if length(a) < length(b)
return true
elseif length(a) > length(b)
return false
else
return nothing
end
end
function part1(lines)
n_pairs = (length(lines) + 1) ÷ 3
right_orders = Vector{Bool}()
for i in 1:n_pairs
a = eval(Meta.parse(lines[i * 3 - 2]))
b = eval(Meta.parse(lines[i * 3 - 1]))
result = is_right_order(a, b)
push!(right_orders, result)
end
return sum(right_orders .* collect(1:n_pairs))
end
function part2(lines)
unordered = Vector{Vector}()
n_pairs = (length(lines) + 1) ÷ 3
for i in 1:n_pairs
push!(unordered, eval(Meta.parse(lines[i * 3 - 2])))
push!(unordered, eval(Meta.parse(lines[i * 3 - 1])))
end
push!(unordered, [[2]])
push!(unordered, [[6]])
ordered = sort(unordered, lt=is_right_order)
return prod(findall(x -> x == [[2]] || x == [[6]], ordered))
end
example = readlines("examples/13.txt")
input = readlines("inputs/13.txt")
@assert part1(example) == 13
println(part1(input))
@assert part2(example) == 140
println(part2(input))