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.
Consider your entire calibration document. What is the sum of all of the calibration values?
SELECT SUM(LEFT(r, 1)::int * 10 + RIGHT(r, 1)::int) AS part1
FROM (
SELECT regexp_replace(input, '[^\d]', '', 'g') AS r
FROM aoc_1201
);
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.
WITH
lines AS (
SELECT regexp_split_to_table(input, '\n') AS line
FROM aoc_1201
),
slices AS (
SELECT line, index, substring(line, index, width) AS slice
FROM
lines,
generate_series(1, length(line)) AS index,
generate_series(1, 5) AS width
),
numbers (t, n) AS (
VALUES ('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9),
('zero', 0), ('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5), ('six', 6), ('seven', 7), ('eight', 8), ('nine', 9)
),
findings AS (
SELECT line, index, n AS number
FROM slices, numbers
WHERE slices.slice = numbers.t
),
first AS ( SELECT DISTINCT ON (line) line, number AS f FROM findings ORDER BY line, index ),
last AS ( SELECT DISTINCT ON (line) line, number AS l FROM findings ORDER BY line, index DESC )
SELECT SUM(f * 10 + l)
FROM first, last
WHERE first.line = last.line
Day 1 was brought to you by: @chaas, @def-, @doy-materialize, @frankmcsherry, @josharenberg, @morsapaes, @nrainer-materialize