-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.rb
34 lines (27 loc) · 1.04 KB
/
day7.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
lines = File.open('inputs/day7.txt').readlines
.map { |l| { :outcome => l.split(':')[0].to_i, :numbers => l.split(':')[1].split(' ').map(&:to_i) } }
def all_options(operators, numbers)
operators.repeated_permutation(numbers.count - 1).to_a
end
def evaluate_left_to_right(numbers, option)
last = numbers[0]
((0..numbers.count - 2).map do |index|
if option[index] == '+'
outcome = last + numbers[index+1]
elsif option[index] == '*'
outcome = last * numbers[index+1]
else # ||
outcome = (last.to_s + numbers[index+1].to_s).to_i
end
last = outcome
end).last
end
def is_solvable(line, operators)
outcome = line[:outcome]
numbers = line[:numbers]
all_options(operators, numbers).any? { |option| evaluate_left_to_right(numbers, option) == outcome } ? outcome : 0
end
operators = %w[+ *]
puts "Part 1: #{lines.sum { |line| is_solvable(line, operators) }}"
operators = %w[+ * ||]
puts "Part 2: #{lines.sum { |line| is_solvable(line, operators) }}"