index.js (1983B)
1 #!/usr/bin/env node 2 3 const fs = require('node:fs'); 4 5 String.prototype.splice = function (start, deleteCount, ...newElements) { 6 return this.slice(0, start) + `${(newElements||[]).join('')}` + this.slice(start + deleteCount); 7 } 8 9 const input = fs 10 .readFileSync('input', 'utf-8') 11 .split('\r\n').join('\n') 12 .split('\r').join('\n') 13 .split('\n') 14 .filter(e => e) 15 16 // Copy & turn into character array 17 const part1map = [ 18 ...input.map(line => line.split('')) 19 ]; 20 21 // Copy & turn into character array 22 const part2map = [ 23 ...input.map(line => line 24 .split('') 25 .map(char => char === 'S' ? 1 : 0) 26 ) 27 ]; 28 29 let totalSplits = 0; 30 31 for(let lineIdx = 1 ; lineIdx < part1map.length ; lineIdx++) { 32 for(let charIdx = 0 ; charIdx < part1map[lineIdx].length ; charIdx++) { 33 34 switch(`${part1map[lineIdx-1][charIdx]}${part1map[lineIdx][charIdx]}`) { 35 case 'S.': 36 case '|.': 37 case '||': 38 part1map[lineIdx][charIdx] = '|'; 39 part2map[lineIdx][charIdx] += part2map[lineIdx-1][charIdx]; 40 break; 41 case '|^': 42 part1map[lineIdx][charIdx-1] = '|'; 43 part1map[lineIdx][charIdx+1] = '|'; 44 part2map[lineIdx][charIdx-1] += part2map[lineIdx-1][charIdx]; 45 part2map[lineIdx][charIdx+1] += part2map[lineIdx-1][charIdx]; 46 totalSplits++; 47 break; 48 case '^.': 49 case '.^': 50 case '.|': 51 case '..': 52 // Intentionally empty 53 break; 54 default: 55 throw new Error(`Unhandled case: ${part1map[lineIdx-1][charIdx]}${part1map[lineIdx][charIdx]}`); 56 } 57 58 } 59 } 60 61 const part1 = totalSplits; 62 console.log(`${part1map.map(line => line.join('')).join('\n')}`); 63 console.log(`${part2map.map(line => line.map(n => n.toString(36)).join('')).join('\n')}`); 64 65 const timelines = part2map.slice(-1)[0].reduce((r,a)=>r+a,0); 66 const part2 = timelines; 67 68 process.stdout.write(`\n\n`); 69 process.stdout.write(`------[ Part 1: ${part1} ]------\n`); 70 process.stdout.write(`------[ Part 2: ${part2} ]------\n`);