2023-12-01

Table of Contents

1. 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:

1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet

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

2. Anwser

Ruby:

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)


3. 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:

two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixtee

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?

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)

Date: 2023-12-01 Fri 00:00

Author: Terry Fung

Created: 2024-11-10 Sun 14:09

Emacs 29.4 (Org mode 9.6.15)

Validate