I’ll just say up front that I never finish the whole Advent of Code. I’m usually good for a few weeks and then they get really hard and life gets busy because of the holidays. So, with my excuses out of the way here is my solution to Day 1 of the Advent of Code.
Part One
const testInput = `1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet`;
const numberWords = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
};
const extractNumbers = input => {
const allMatches =
input.match(/[1-9]|one|two|three|four|five|six|seven|eight|nine/gi) || [];
return allMatches.map(match =>
isNaN(match) ? numberWords[match.toLowerCase()] : Number(match)
);
};
const concatFirstAndLastNumber = arr => {
return Number(`${arr[0]}${arr[arr.length - 1]}`);
};
const total = input => {
return input
.split("\n")
.map(extractNumbers)
.map(concatFirstAndLastNumber)
.reduce((acc, curr) => acc + curr, 0);
};
console.log(total(testInput)); // 142
Part 2
const testInput = `two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
sdoneight37`;
const numberWords = {
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
nine: 9,
oneight: 18,
twone: 21,
threeight: 38,
fiveight: 58,
sevenine: 79,
eightwo: 82,
eighthree: 83,
nineight: 98,
};
const extractNumbers = input => {
const allMatches =
input.match(/[1-9]|one|two|three|four|five|six|seven|eight|nine/gi) || [];
return allMatches.map(match =>
isNaN(match) ? numberWords[match.toLowerCase()] : Number(match)
);
};
const concatFirstAndLastNumber = arr => {
return Number(`${arr[0]}${arr[arr.length - 1]}`);
};
const solve = input => {
input = input.replace(
/oneight|twone|threeight|fiveight|sevenine|eightwo|eighthree|nineight/gi,
matched => numberWords[matched]
);
return input
.split("\n")
.map(extractNumbers)
.map(concatFirstAndLastNumber)
.reduce((acc, curr) => acc + curr, 0);
};
console.log(solve(testInput)); // 298
I slightly altered the puzzles given input to take into account a case where the spelled numbers could possibly run together. This tripped me up on my first attempt because I didn’t think about cases like oneight, fiveight, nineight, etc.