aoc2023/day_1/impl_2.rb

45 lines
828 B
Ruby
Raw Normal View History

2023-12-01 10:00:04 +01:00
MAPPER = {
"8": "eight",
"7": "seven",
"3": "three",
"9": "nine",
"5": "five",
"4": "four",
"6": "six",
"2": "two",
"1": "one"
}
#prepare the input which is a string containing new lines
def parse(input)
data = []
input.each_line do |line|
data << line.chomp
end
data
end
def find_first_digit(line, reverse:false)
line.length.times do |i|
j = reverse ? line.length - 1 - i : i
return line[j] if line[j].to_i != 0
sub_line = line[j..-1]
MAPPER.each do |k,v|
return k if sub_line.start_with?(v)
end
end
end
# result should a single string or integer
def calculate(data)
result = 0
data.each_with_index do |d,i|
first = find_first_digit(d)
last = find_first_digit(d, reverse: true)
num = "#{first}"+"#{last}"
result += num.to_i
end
result
end