part-02.ts (2105B)
1 import { lineByLine } from './line-by-line'; 2 import { weightedValues } from './weighted-values'; 3 import { mostWeightedValue } from './most-weighted-value'; 4 5 (async () => { 6 7 // Read whole input into memory this time 8 const storage = []; 9 await lineByLine(__dirname + '/input', line => { 10 if (!line) return; 11 storage.push(line.split('').map(v => parseInt(v, 2))); 12 }); 13 14 // The things we need to filter 15 let oxygenReadings = storage.slice(); 16 let scrubberReadings = storage.slice(); 17 18 // Filter the oxygen readings 19 for(let idx = 0 ; oxygenReadings.length > 1 ; idx++) { 20 const column = oxygenReadings.map(a => a[idx]); 21 const weights = weightedValues(column); 22 let mostCommon = mostWeightedValue(weights, false); 23 24 // Equal = 1, as specified 25 if (mostCommon === undefined) { 26 mostCommon = 1; 27 } 28 29 // Remove non-matching values 30 oxygenReadings = oxygenReadings.filter(v => v[idx] == mostCommon); 31 } 32 33 // Filter the scrubber readings 34 for(let idx = 0 ; scrubberReadings.length > 1 ; idx++) { 35 const column = scrubberReadings.map(a => a[idx]); 36 const weights = weightedValues(column); 37 let mostCommon = mostWeightedValue(weights, false); 38 39 // Equal = 1, as inverted of specified 40 if (mostCommon === undefined) { 41 mostCommon = 1; 42 } 43 44 // Invert, we're working binary-ish 45 const leastCommon = (!mostCommon) | 0; 46 47 // Remove non-matching values 48 scrubberReadings = scrubberReadings.filter(v => v[idx] == leastCommon); 49 } 50 51 // Convert into numbers again 52 const oxygenRating = parseInt(oxygenReadings[0].join(''), 2); 53 const scrubberRating = parseInt(scrubberReadings[0].join(''), 2); 54 const lifeSupportRating = oxygenRating * scrubberRating; 55 56 process.stdout.write('\n\n'); 57 process.stdout.write('---[ REPORT ]---\n'); 58 process.stdout.write('\n'); 59 process.stdout.write(`oxygen rating : ${oxygenRating}\n`); 60 process.stdout.write(`scrubber rating : ${scrubberRating}\n`); 61 process.stdout.write(`life support rating : ${lifeSupportRating}\n`); 62 process.stdout.write('\n'); 63 64 })(); 65