From d269f0b3219ea030818aabce255b2080056214bc Mon Sep 17 00:00:00 2001 From: Philip Corliss Date: Fri, 1 Dec 2023 00:17:31 -0600 Subject: [PATCH] 2023 Day 01 Part 2 Complete --- 2023/01/spec/trebuchet_spec.rb | 26 ++++++++++++++++++++++++++ 2023/01/trebuchet.rb | 24 +++++++++++++++++++++--- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/2023/01/spec/trebuchet_spec.rb b/2023/01/spec/trebuchet_spec.rb index dab66af..782e683 100644 --- a/2023/01/spec/trebuchet_spec.rb +++ b/2023/01/spec/trebuchet_spec.rb @@ -13,8 +13,21 @@ EOS } + let(:input2) { + <<~EOS + two1nine + eightwothree + abcone2threexyz + xtwone3four + 4nineeightseven2 + zoneight234 + 7pqrstsixteen + EOS + } + describe Advent::Trebuchet do let(:ad) { Advent::Trebuchet.new(input) } + let(:ad2) { Advent::Trebuchet.new(input2) } describe "#new" do end @@ -28,12 +41,25 @@ ad = Advent::Trebuchet.new("12abc2") expect(ad.nums).to eq([12]) end + + it "extracts digits as strings" do + expect(ad2.nums).to eq([29, 83, 13, 24, 42, 14, 76]) + end + + it "handles strings with overlapping numbers" do + ad = Advent::Trebuchet.new("haseightwoeightwohas") + expect(ad.nums).to eq([82]) + end end context "validation" do it "validates part1 examples" do expect(ad.sum).to eq(142) end + + it "validates part2 examples" do + expect(ad2.sum).to eq(281) + end end end end diff --git a/2023/01/trebuchet.rb b/2023/01/trebuchet.rb index 16e104a..f6eb975 100644 --- a/2023/01/trebuchet.rb +++ b/2023/01/trebuchet.rb @@ -12,11 +12,29 @@ def initialize(input) @lines = input.each_line.map(&:strip) end + STRING_TO_NUM = { + "one" => 1, + "two" => 2, + "three" => 3, + "four" => 4, + "five" => 5, + "six" => 6, + "seven" => 7, + "eight" => 8, + "nine" => 9, + } + START_REGEX = /^.*?(one|two|three|four|five|six|seven|eight|nine|\d)/ + END_REGEX = /.*(one|two|three|four|five|six|seven|eight|nine|\d)/ + def nums @nums ||= @lines.map do |line| - numbers_in_string = line.scan(/\d/).map(&:to_i) - a = numbers_in_string.first - b = numbers_in_string.last + line.match(START_REGEX) + a = $1 + a = STRING_TO_NUM.has_key?(a) ? STRING_TO_NUM[a] : a.to_i + line.match(END_REGEX) + b = $1 + b = STRING_TO_NUM.has_key?(b) ? STRING_TO_NUM[b] : b.to_i + a * 10 + b end end