-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
de18bb6
commit b7bd784
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
lines = STDIN.read.split("\n") | ||
|
||
ADD = '+' | ||
MUL = '*' | ||
CON = '||' | ||
P1_OPTS = [ADD, MUL] | ||
P2_OPTS = [ADD, MUL, CON] | ||
|
||
def total_calibration(equations, possible_operators) | ||
result = 0 | ||
equations.each do |(test_value, operands)| | ||
choices = possible_operators.repeated_permutation(operands.size - 1) | ||
choices.each do |operators| | ||
res = operators.zip(operands[1..]).reduce(operands.first) do |acc, (opt, opd)| | ||
case opt | ||
when ADD | ||
acc += opd | ||
when MUL | ||
acc *= opd | ||
else | ||
acc = (acc.to_s + opd.to_s).to_i | ||
end | ||
end | ||
|
||
if res == test_value | ||
result += res | ||
break | ||
end | ||
end | ||
end | ||
result | ||
end | ||
|
||
equations = lines.map do |line| | ||
l, r = line.split(':') | ||
[l.to_i, r.split.map(&:to_i)] | ||
end | ||
|
||
puts total_calibration(equations, P1_OPTS) | ||
puts total_calibration(equations, P2_OPTS) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
190: 10 19 | ||
3267: 81 40 27 | ||
83: 17 5 | ||
156: 15 6 | ||
7290: 6 8 6 15 | ||
161011: 16 10 13 | ||
192: 17 8 14 | ||
21037: 9 7 18 13 | ||
292: 11 6 16 20 |