-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_09.rb
73 lines (67 loc) · 1.5 KB
/
day_09.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
def step1(example = false)
lines = []
input(example).each do |line|
lines << line.split(' ').map(&:to_i)
end
result = []
lines.each do |line|
row = find_result_per_line(line)
result << extrapolate(row)
end
p result
p result.collect{|l| l.first.last}.sum
end
def find_result_per_line(line)
matrix = [line]
matrix.each_with_index do |line, index|
if line.all? { |char| char == 0 }
next
else
new_line = []
line.each_with_index do |char, index|
break if index == line.size - 1
new_line << line[index+1] - line[index]
end
matrix << new_line
end
end
end
def extrapolate(matrix, back = false)
result = []
matrix.reverse.each_with_index do |line, index|
if back
if index == 0
line.unshift(0)
else
new_value = line.first - matrix.reverse[index - 1].first
line.unshift(new_value)
end
else
if index == 0
line << 0
else
new_value = matrix.reverse[index - 1].last + line.last
line << new_value
end
end
result << line
break if index == matrix.size - 1
end
result.reverse
end
def step2(example = false)
lines = []
input(example).each do |line|
lines << line.split(' ').map(&:to_i)
end
result = []
lines.each do |line|
row = find_result_per_line(line)
result << extrapolate(row, true)
end
# p result
p result.collect{|l| l.first.first}.sum
end
def input(example)
example == 'example' ? @input_example : @input
end