48 lines
1009 B
JavaScript
48 lines
1009 B
JavaScript
const fs = require("fs");
|
|
const filePath = "data.txt";
|
|
const BITS = 12;
|
|
let gammaRate = '';
|
|
let epsilonRate= '';
|
|
|
|
|
|
|
|
fs.readFile(filePath,"utf-8", (err, data)=>{
|
|
let binaryArray = data.split("\n");
|
|
|
|
|
|
|
|
// O (N*5)
|
|
for(let bit = 0; bit < BITS ; bit++ ){
|
|
let bitIs1= 0;
|
|
let bitIs0= 0;
|
|
|
|
for( let i = 0; i < binaryArray.length; i++){
|
|
|
|
if ( binaryArray[i][bit] == '1'){
|
|
bitIs1++;
|
|
} else {
|
|
bitIs0 ++;
|
|
}
|
|
}
|
|
|
|
|
|
if( bitIs1 > bitIs0){
|
|
gammaRate += '1';
|
|
epsilonRate += '0'
|
|
}else{
|
|
gammaRate += '0';
|
|
epsilonRate += '1'
|
|
|
|
}
|
|
|
|
|
|
}
|
|
console.log(`Gamma (bin):${gammaRate}, Epsilon (bin): ${epsilonRate}`)
|
|
let gamma = parseInt(gammaRate ,2);
|
|
let epsilon = parseInt(epsilonRate, 2);
|
|
console.log(` Gamma: ${gamma}, Epsilon: ${epsilon}`);
|
|
|
|
let result = gamma*epsilon;
|
|
console.log(`Result ${result}`);
|
|
|
|
}); |