diff --git a/src/advent/day1.rb b/src/advent/day1.rb index 33c69cb..57d6ed5 100644 --- a/src/advent/day1.rb +++ b/src/advent/day1.rb @@ -1,15 +1,33 @@ # frozen_string_literal: true -def fist_letter(line) - line.split("").each do |x| - if x.match?(/\d/) - return x +DIGIT_NAMES = {one: "1", two: "2", three: "3", four: "4" , + five: "5", six: "6", seven: "7", eight: "8", + nine: "9"} +def extracts_digits (word, ret=[]) + if word == nil || word.empty? + return ret + end + if word.start_with? /\d/ + ret.append word[0] + return extracts_digits word[1..], ret + end + + DIGIT_NAMES.each do |name, value| + if word.start_with? name.to_s + ret.append value + return extracts_digits word[1..], ret end end + extracts_digits word[1..], ret +end + + +def fist_letter(line) + extracts_digits(line)[0] end def last_digit(line) - fist_letter line.reverse + extracts_digits(line)[-1] end def get_calibration_code(line) @@ -27,7 +45,15 @@ def get_sum_of_calibration_code(document) calibration_codes.reduce 0, :+ end +# puts "on".length + +# puts extracts_digits "7pqrstsixteen" +mock_input = " +8nine37bpkmtghhnc2hnreightwohvs +" + input_file_name = File.join(File.dirname(__FILE__), "day_1_input.txt") input_content = File.open(input_file_name).read -puts get_sum_of_calibration_code(input_content) \ No newline at end of file +puts get_sum_of_calibration_code(input_content) +# puts extracts_digits mock_input \ No newline at end of file