index.js (1925B)
1 #!/usr/bin/env node 2 3 const fs = require('node:fs'); 4 5 const banks = fs 6 .readFileSync('input', 'utf-8') 7 .split('\r\n').join('\n') 8 .split('\r').join('\n') 9 .split('\n') 10 .map(str => str.trim()) 11 .filter(str => str) 12 .map(bank => ({ 13 batteries: bank, 14 })) 15 ; 16 17 // Part 1 18 for(const bank of banks) { 19 // Find the tens 20 let highestTensVal = -1; 21 let highestTensIdx = -1; 22 for(const rating of ['9','8','7','6','5','4','3','2','1']) { 23 const found = bank.batteries.indexOf(rating); 24 if (found < 0) continue; 25 if (found == (bank.batteries.length-1)) continue; 26 highestTensVal = rating; 27 highestTensIdx = found; 28 break; 29 } 30 // Find the ones 31 let highestOnesVal = -1; 32 let highestOnesIdx = -1; 33 34 for(const rating of ['9','8','7','6','5','4','3','2','1']) { 35 const found = bank.batteries.indexOf(rating, highestTensIdx+1); 36 if (found < 0) continue; 37 highestOnesVal = rating; 38 highestOnesIdx = found; 39 break; 40 } 41 42 // Save it for the records 43 bank.joltage2 = parseInt(`${highestTensVal}${highestOnesVal}`, 10); 44 } 45 46 // Part 2 47 for(const bank of banks) { 48 49 let construct = []; 50 let currentIdx = -1; 51 while(construct.length < 12) { 52 let found = -1; 53 for(const rating of ['9','8','7','6','5','4','3','2','1']) { 54 found = bank.batteries.indexOf(rating, currentIdx + 1); 55 if (found < 0) continue; 56 if (found >= (bank.batteries.length + construct.length - 11)) { 57 found = -1; 58 continue; 59 }; 60 currentIdx = found; 61 construct.push(rating); 62 break; 63 } 64 if (found < 0) { 65 throw new Error("Could not find highest number"); 66 } 67 } 68 69 bank.joltage12 = BigInt(construct.join('')); 70 } 71 72 const part1 = banks.reduce((r,bank) => r+bank.joltage2, 0); 73 const part2 = banks.reduce((r,bank) => r+bank.joltage12, 0n); 74 75 process.stdout.write(`------[ Part 1: ${part1} ]------\n`); 76 process.stdout.write(`------[ Part 2: ${part2} ]------\n`);