-
Notifications
You must be signed in to change notification settings - Fork 0
/
03b_solution.rb
75 lines (60 loc) · 1.17 KB
/
03b_solution.rb
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
input = File.read("./03input.txt").split("\n").map { |line| line.split("").map(&:to_i) }
width = input[0].length
range = 0..(width-1)
def reduce(input, pos)
output = []
no0 = 0
no1 = 0
input.each do |line|
if line[pos] == 0
no0 += 1
else
no1 += 1
end
end
input.each do |line|
yield output, line, pos, no0, no1
end
output
end
oxygen = input
range.each do |pos|
break if oxygen.count == 1
oxygen = reduce(oxygen, pos) do |output, line, pos, no0, no1|
if no0 == no1
if line[pos] == 1
output << line
end
elsif no0 > no1
if line[pos] == 0
output << line
end
else
if line[pos] == 1
output << line
end
end
end
end
oxygen_int = oxygen.join("").to_i(2)
co2 = input
range.each do |pos|
break if co2.count == 1
co2 = reduce(co2, pos) do |output, line, pos, no0, no1|
if no0 == no1
if line[pos] == 0
output << line
end
elsif no0 > no1
if line[pos] == 1
output << line
end
else
if line[pos] == 0
output << line
end
end
end
end
co2_int = co2.join("").to_i(2)
puts oxygen_int * co2_int