Match and Scan - Day 01 - Advent of Code 2023

preview_player
Показать описание
Let's solve Day 1 of Advent of Code 2023 in Ruby! We'll parse a trebuchet calibration log file, extracting the first and last digits from each line, whether they're numerals or spelled-out words. By summing these two-digit numbers, we get the calibration value.

It's a fun logic puzzle with regular expressions, arrays and hashes in a Ruby script. The code is concise but effective for this coding challenge.

Overall it's a great beginner-friendly Advent of Code solution, showing some clever Ruby tricks for this text parsing and calculation problem.

#adventofcode #ruby
Рекомендации по теме
Комментарии
Автор

Love these videos. It's a great way to learn more about the language

jacobdegeling
Автор

Nice to see you again with Advent of Code. 2nd part I did like this:

def search_digit s, m
# m should be :index or :rindex
a = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
digit = nil
index = s.send m, /\d/
digit = s[index].to_i unless index == nil
a.each_with_index{|digitname, i|
j = s.send m, digitname
next if j == nil
if digit == nil || (m == :index && j < index) || (m == :rindex && j > index)
index = j
digit = i+1
end
}
digit
end

sum = 0
while s = gets
s = search_digit(s, :index)*10 + search_digit(s, :rindex)
sum += s
end
puts sum

piotrtalarczyk
Автор

Not a Pythonistra but I thought the following would work.

first = WORD_TO_DIGIT[digits[0]]
last = WORD_TO_DIGIT[digits[-1]]
(first + last).to_i

kwicklaunch