Last active
December 2, 2023 03:46
-
-
Save trescenzi/d91826c755c1afd02aba398a50cd48b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const text = await Deno.readTextFile('./day1'); | |
const digits = new Map(); | |
digits.set('zero', '0'); | |
digits.set('one', '1'); | |
digits.set('two', '2'); | |
digits.set('three', '3'); | |
digits.set('four', '4'); | |
digits.set('five', '5'); | |
digits.set('six', '6'); | |
digits.set('seven', '7'); | |
digits.set('eight', '8'); | |
digits.set('nine', '9'); | |
const lines = text.split('\n'); | |
const sum = lines.reduce((acc, line) => { | |
// we've gotta pad this because we need to be able to backup to | |
// before our splice if the string starts with a number | |
const arr = ['', ...line.split('')]; | |
let i = 0; | |
let firstNum = 0; | |
let lastNum = 0; | |
let curr = ''; | |
while (i <= arr.length) { | |
const x = arr[i]; | |
const isNum = Boolean(parseInt(x)); | |
if (isNum) { | |
// if we've got a number but haven't seen one yet set it as the first | |
// also set it as the last | |
if (firstNum === 0) firstNum = x; | |
lastNum = x; | |
curr = ''; | |
} else { | |
curr += arr[i]; | |
// determine if there's a number in our current string | |
if (digits.has(curr.substring(0,4))) curr = curr.substring(0,4); | |
if (digits.has(curr.substring(1,5))) curr = curr.substring(1,5); | |
if (digits.has(curr.substring(0,3))) curr = curr.substring(0,3); | |
if (digits.has(curr.substring(1,4))) curr = curr.substring(1,4); | |
if (digits.has(curr.substring(2,5))) curr = curr.substring(2,5); | |
if (digits.has(curr)) { | |
const digit = digits.get(curr); | |
const start = Math.max(i - curr.length, 0); | |
// splice out the number leaving the last letter | |
arr.splice(start, curr.length, digit); | |
// back up to before the number we spliced in | |
i = start - 1; | |
curr = ''; | |
} | |
if (curr.length > 4) { | |
curr = curr.substring(1); | |
} | |
} | |
i++; | |
} | |
return parseInt(firstNum + lastNum) + acc; | |
}, 0); | |
console.log(sum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment