Skip to main content TerryFunggg Blog

Advent of Code 2023-12-01

Question

The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.

For example:

code snippet start

    1abc2
    pqr3stu8vwx
    a1b2c3d4e5f
    treb7uchet

code snippet end

In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.

Consider your entire calibration document. What is the sum of all of the calibration values?

Get files

Anwser

ruby code snippet start

def scan(line)
  line = line.to_s
  nums = line.scan /[0-9]/
  return 0 if nums.count == 0

  "#{nums.first}#{nums.last}"
end

File.readlines('input.txt').each do |line|
  counter << scan(line)
end

p counter.sum(&:to_i)

ruby code snippet end

Part two

Your calculation isn’t quite right. It looks like some of the digits are actually spelled out with letters: one, two, three, four, five, six, seven, eight, and nine also count as valid “digits”.

Equipped with this new information, you now need to find the real first and last digit on each line. For example:

code snippet start

    two1nine
    eightwothree
    abcone2threexyz
    xtwone3four
    4nineeightseven2
    zoneight234
    7pqrstsixtee

code snippet end

In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.

What is the sum of all of the calibration values?

ruby code snippet start

counter = []

class String
  @@num_h = {
    one: 1,
    two: 2,
    three: 3,
    four: 4,
    five: 5,
    six: 6,
    seven: 7,
    eight: 8,
    nine: 9
  }

  def to_i

    return @@num_h[self.to_sym] if @@num_h.key? self.to_sym

    Integer(self)
  end
end

REGX = /(?=([0-9]|one|two|three|four|five|six|seven|eight|nine))/

def scan(line)
  line = line.to_s
  nums = line.scan(REGX)

  return 0 if nums.count == "0"
  return "#{nums.first.to_i}#{nums.first.to_i}" if nums.count == 1

  "#{nums.first.to_i}#{nums.last.to_i}"
end


File.readlines('input.txt').each do |line|
  counter << scan(line)
end

p counter.sum(&:to_i)

ruby code snippet end

Day 2 Day 3 Day 4 Day 5

Day 6 Day 7 Day 8 Day 9 Day 10 Day 11