83 lines
1.9 KiB
JavaScript
83 lines
1.9 KiB
JavaScript
const fs = require("fs");
|
|
const filePath = "data.txt";
|
|
const BITS = 12;
|
|
|
|
|
|
|
|
|
|
fs.readFile(filePath,"utf-8", (err, data)=>{
|
|
let binaryArray = data.split("\n");
|
|
|
|
|
|
let numberList = KeepCommon(binaryArray, 0)
|
|
|
|
for(let bit = 1; bit < BITS ; bit++ ){
|
|
numberList = KeepCommon(numberList, bit);
|
|
|
|
}
|
|
let oxygen_generator_rating = numberList[0];
|
|
|
|
|
|
|
|
let numberList2 = KeepLeastCommon(binaryArray, 0);
|
|
|
|
for(let bit = 1; bit < BITS; bit++){
|
|
numberList2 = KeepLeastCommon(numberList2, bit);
|
|
}
|
|
|
|
CO2_scrubber_rating = numberList2[0];
|
|
|
|
console.log(`Oxygen number: ${oxygen_generator_rating}, CO2 Scubber rating: ${CO2_scrubber_rating }`);
|
|
|
|
oxygen_generator_rating = parseInt(oxygen_generator_rating ,2);
|
|
CO2_scrubber_rating = parseInt(CO2_scrubber_rating, 2);
|
|
console.log(` Oxygen: ${oxygen_generator_rating},CO2: ${CO2_scrubber_rating}`);
|
|
|
|
let result = oxygen_generator_rating*CO2_scrubber_rating;
|
|
console.log(`Result ${result}`);
|
|
|
|
});
|
|
|
|
function KeepCommon(binaryArray, bit){
|
|
let hasOnes = [];
|
|
let hasZeros= [];
|
|
for( let i = 0; i < binaryArray.length; i++){
|
|
|
|
if ( binaryArray[i][bit] == '1'){
|
|
hasOnes.push(binaryArray[i]);
|
|
} else {
|
|
hasZeros.push(binaryArray[i]);
|
|
}
|
|
}
|
|
|
|
|
|
if( hasZeros.length > hasOnes.length){
|
|
return hasZeros;
|
|
}else{
|
|
return hasOnes;
|
|
}
|
|
}
|
|
|
|
function KeepLeastCommon(binaryArray, bit){
|
|
if( binaryArray.length == 1 )
|
|
return binaryArray;
|
|
|
|
let hasOnes = [];
|
|
let hasZeros= [];
|
|
for( let i = 0; i < binaryArray.length; i++){
|
|
|
|
if ( binaryArray[i][bit] == '1'){
|
|
hasOnes.push(binaryArray[i]);
|
|
} else {
|
|
hasZeros.push(binaryArray[i]);
|
|
}
|
|
}
|
|
|
|
|
|
if( hasZeros.length > hasOnes.length){
|
|
return hasOnes;
|
|
}else{
|
|
return hasZeros;
|
|
}
|
|
}
|