-
Notifications
You must be signed in to change notification settings - Fork 0
/
3.jl
66 lines (52 loc) · 1.24 KB
/
3.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
function slurp_grid(filename)
permutedims(hcat(map(collect, readlines(filename))...))
end
eg = slurp_grid("3eg.txt")
input = slurp_grid("3a.txt")
flip(bitchar) = bitchar == '1' ? '0' : '1'
gamma(col) = length(filter(==('1'), col)) / length(col) >= 0.5 ? '1' : '0'
function gamma_rate(m)
map(gamma, eachcol(m))
end
function to_decimal(bits)
bitstring = string(bits...)
parse(Int, bitstring, base = 2)
end
function solve1(m)
g = gamma_rate(m)
epsilon_rate = map(flip, g)
to_decimal(g) * to_decimal(epsilon_rate)
end
solve1(eg)
solve1(input)
function select_max(m, idx)
max = gamma(m[:, idx])
permutedims(hcat([row for row in eachrow(m) if row[idx] == max]...))
end
function select_min(m, idx)
min = flip(gamma(m[:, idx]))
permutedims(hcat([row for row in eachrow(m) if row[idx] == min]...))
end
function oxygen(m)
s = size(m, 2)
for idx = 1:s
m = select_max(m, idx)
if size(m, 1) == 1
return m
end
end
end
function co2(m)
s = size(m, 2)
for idx = 1:s
m = select_min(m, idx)
if size(m, 1) == 1
return m
end
end
end
function solve2(m)
to_decimal(oxygen(m)) * to_decimal(co2(m))
end
solve2(eg)
solve2(input) == 1613181