Skip to content

Instantly share code, notes, and snippets.

@drio
Last active December 6, 2023 15:49
Show Gist options
  • Save drio/79a0be84e99f279da71750ec96009b63 to your computer and use it in GitHub Desktop.
Save drio/79a0be84e99f279da71750ec96009b63 to your computer and use it in GitHub Desktop.
Advent of code - day 1 2023
import { pretty, linesFromStdin } from '../common.js';
const listNums = "zero, one, two, three, four, five, six, seven, eight, nine".split(",").map(e => e.trim())
function findMatches(line, str) {
const re = new RegExp(str, "g");
const matches = [...line.matchAll(re)]
return matches.map(({ index }) => ({ s: index }))
}
function findWordDigits(line) {
const a = []
for (let i = 0; i < listNums.length; i++) {
const wordNumber = listNums[i]
const matches = findMatches(line, wordNumber)
matches.forEach(({ s }) => {
a.push({
s: s,
end: s + wordNumber.length - 1,
d: i
});
})
}
return a.map(o => o).sort((a, b) => a.s - b.s)
}
function findDigits(line) {
const a = []
line.split("").forEach((c, i) => {
const d = +c
if (d >= 0 && d <= 9) a.push({ s: i, d: d })
})
return a
}
function doWork(lines) {
let sum = 0
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
if (line === "") break
const o = [...findWordDigits(line), ...findDigits(line)]
.map(o => o)
.sort((a, b) => a.s - b.s);
const r = +[o[0], o[o.length - 1]].map(({ d }) => d).join("")
sum += r
}
console.log(sum)
}
function test(input) {
for (let i = 0; i < input.length; i++) {
const [expected, line] = input[i]
const o = [...findWordDigits(line), ...findDigits(line)]
.map(o => o)
.sort((a, b) => a.s - b.s)
const r = +[o[0], o[o.length - 1]].map(({ d }) => d).join("")
console.log(line, `e=${expected} r=${r}`, expected === r, pretty(o))
}
}
const testInput = [
[29, 'two1nine'],
[83, 'eightwothree'],
[13, 'abcone2threexyz'],
[24, 'xtwone3four'],
[42, '4nineeightseven2'],
[14, 'zoneight234'],
[76, '7pqrstsixteen'],
[98, '9oneight'],
[55, 'frqhlvzrjrxfive2three5g'],
[28, "twofourthree778nineeight"],
[86, '896'],
[69, 'sixrrmlkptmc18zhvninek'],
[82, 'jcb82eightwond'],
[29, 'gqhtwone11ninethree4ptjsqlg4fivenine'],
[46, 'fourdvhzp7foursix']
]
doWork(linesFromStdin())
//test(testInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment