Part 2
This commit is contained in:
parent
f3b7f68188
commit
2fd8a6225a
@ -2,4 +2,5 @@
|
|||||||
require "cephalopod_math"
|
require "cephalopod_math"
|
||||||
|
|
||||||
cephalopod_math = CephalopodMath.for STDIN.read.chomp
|
cephalopod_math = CephalopodMath.for STDIN.read.chomp
|
||||||
puts "Part 1: #{cephalopod_math.wide_column_answers.sum}"
|
puts "Part 1: #{cephalopod_math.wide_problem_answers.sum}"
|
||||||
|
puts "Part 2: #{cephalopod_math.narrow_problem_answers.sum}"
|
||||||
|
|||||||
@ -8,11 +8,38 @@ class CephalopodMath
|
|||||||
new input
|
new input
|
||||||
end
|
end
|
||||||
|
|
||||||
def wide_columns
|
def wide_problem_answers
|
||||||
worksheet.split("\n").map(&:split).transpose
|
problems.map do |problem|
|
||||||
|
problem[..-2].map(&:to_i).reduce(&(problem[-1].strip.to_sym))
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def wide_column_answers
|
def narrow_problem_answers
|
||||||
wide_columns.map{ |column| column[..-2].map(&:to_i).reduce(&(column[-1]).to_sym) }
|
problems.map do |problem|
|
||||||
|
operator = problem[-1].strip.to_sym
|
||||||
|
numbers = problem[..-2].map { |line| line.split("") }.transpose.map { |line| line.join("").to_i }.reject(&:zero?)
|
||||||
|
numbers.reduce operator
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def problem_widths
|
||||||
|
@problem_widths ||= operator_line.split("+").map { |c| c.split "*" }.flatten.map(&:length)[1..]
|
||||||
|
end
|
||||||
|
|
||||||
|
def problems
|
||||||
|
@problems ||= lines.map(&:clone).map do |line|
|
||||||
|
problem_widths.reduce([]) do |chunks, problem_width|
|
||||||
|
slice = line.slice!(0, problem_width + 1)
|
||||||
|
chunks << slice
|
||||||
|
end
|
||||||
|
end.transpose
|
||||||
|
end
|
||||||
|
|
||||||
|
def operator_line
|
||||||
|
lines.last
|
||||||
|
end
|
||||||
|
|
||||||
|
def lines
|
||||||
|
worksheet.split("\n")
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user