Public
Edited
Dec 2, 2023
Insert cell
Insert cell
Insert cell
function reverse(line) {
return [...line].reverse().join("");
}
Insert cell
Insert cell
function extractDigits(lines) {
return lines.map((s) => Number(s.match(/\d/) + reverse(s.match(/\d/))));
}
Insert cell
Insert cell
function part1(input) {
return AOC.sum(extractDigits(input.split("\n")));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
words = "one,two,three,four,five,six,seven,eight,nine".split(",")
Insert cell
Insert cell
lookup = words.map(reverse).reduce(
(lu, w, i) => ({ ...lu, [w]: `${i + 1}` }),
words.reduce((lu, w, i) => ({ ...lu, [w]: `${i + 1}` }), {})
)
Insert cell
Insert cell
function extractWordsAndDigits(lines) {
const fMatch = RegExp(words.join("|") + "|\\d");
const rMatch = RegExp(words.map(reverse).join("|") + "|\\d");
const toDigit = (token, regex) => {
const digit = token.match(regex)[0];
return digit.length === 1 ? digit : lookup[digit];
};
return lines.map((s) =>
Number(toDigit(s, fMatch) + toDigit(reverse(s), rMatch))
);
}
Insert cell
function part2(input) {
return AOC.sum(extractWordsAndDigits(input.split("\n")));
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more