Code solution
Part 1
const fs = require('fs');
function countValues() {
const vals = fs.readFileSync('day1-input.txt', 'utf8').split('\n');
return vals.reduce((acc, val) => {
let res = [];
for (const char of val) {
if (/^\d+$/.test(char)) {
res.push(char);
}
}
return acc += parseInt(res[0] + res[res.length - 1]);
}, 0);
}
Part 2
function countValuesPart2() {
const vals = fs.readFileSync('day1-input.txt', 'utf8').split('\n');
const map = new Map([
['one', '1'],
['two', '2'],
['three', '3'],
['four', '4'],
['five', '5'],
['six', '6'],
['seven', '7'],
['eight', '8'],
['nine', '9']
]);
return vals.reduce((acc, val) => {
let first = val.match(/\d|one|two|three|four|five|six|seven|eight|nine/)[0];
let last = val.match(/.*(\d|one|two|three|four|five|six|seven|eight|nine)/)[1];
if (map.has(first)) first = map.get(first);
if (map.has(last)) last = map.get(last);
return acc += parseInt(first + last);
}, 0);
}
Key Takeaways
- Regex can be king for these problems.
- Keep it simple, the part two only asks for the first and last number, so work the soltuion around that. The regex does this by using the
.*it stores all the matches atlast[0]and then the last match atlast[1]. I could have gone with a more iterative approach through the array but that would just include more complexity and overhead than necessary.

