this repo has no description
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

at main 49 lines 1.6 kB view raw
1/* Your calculation isn't quite right. It looks like some of the digits are actually spelled out with letters: one, two, three, four, five, six, seven, eight, and nine also count as valid "digits". 2 3Equipped with this new information, you now need to find the real first and last digit on each line. For example: 4 5two1nine 6eightwothree 7abcone2threexyz 8xtwone3four 94nineeightseven2 10zoneight234 117pqrstsixteen 12 13In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281. 14 15What is the sum of all of the calibration values? */ 16 17const digitMap = { 18 one: '1', 19 two: '2', 20 three: '3', 21 four: '4', 22 five: '5', 23 six: '6', 24 seven: '7', 25 eight: '8', 26 nine: '9', 27}; 28 29const allNumbersRegex = `(${Object.keys(digitMap).join('|')}|${Object.values(digitMap).join('|')})`; 30const input = await Bun.file('1.input').text(); 31// const input = await Bun.file('1part2test.input').text(); 32const splitInput = input.split('\n'); 33let counter = 0; 34for (let line of splitInput) { 35 // positive lookahead wizardry needed to capture things like "twone" 36 // https://stackoverflow.com/a/33903830 37 const regex = new RegExp(`(?=${allNumbersRegex})`, 'g'); 38 const matches = Array.from(line.matchAll(regex), (x) => x[1]); 39 let firstDigit = matches.at(0); 40 let lastDigit = matches.at(-1); 41 for (const [key, value] of Object.entries(digitMap)) { 42 firstDigit = firstDigit!.replace(key, value); 43 lastDigit = lastDigit!.replace(key, value); 44 } 45 const lineValue = parseInt(`${firstDigit}${lastDigit}`, 10); 46 counter += lineValue; 47} 48 49console.log(counter);