Skip to content

Commit

Permalink
2023 Day 01 Part 2 Complete
Browse files Browse the repository at this point in the history
  • Loading branch information
pcorliss committed Dec 1, 2023
1 parent f2cff93 commit d269f0b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
26 changes: 26 additions & 0 deletions 2023/01/spec/trebuchet_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
24 changes: 21 additions & 3 deletions 2023/01/trebuchet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d269f0b

Please sign in to comment.