Created
December 7, 2021 04:18
-
-
Save mentalclear/5989e19a424f105827f97427d1d21b57 to your computer and use it in GitHub Desktop.
Solution for "Advent of Code" Day 3 Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let fs = require("fs") | |
const readFileLines = filename => | |
fs.readFileSync(filename) | |
.toString('utf-8') | |
.split('\n'); | |
let inputArray = readFileLines('C:\\AdventOfCode\\day3.txt'); | |
function countResult(inputArray, gamma_epsilon) { | |
const arrays = [[], [], [], [], [], [], [], [], [], [], [], []]; | |
let result = ''; | |
let current = []; | |
for (let i = 0; i < inputArray.length; i++) { | |
current = inputArray[i].split(''); | |
for (let j = 0; j < current.length; j++) { | |
arrays[j].push(current[j]); | |
} | |
} | |
const decision = (arr, decide) => { | |
let zeros = 0; | |
let ones = 0; | |
arr.forEach(digit => { | |
if (Number(digit) === 0) zeros += 1; | |
else ones += 1; | |
}); | |
if (decide === "gamma") { | |
if (zeros > ones) return "0" | |
else return "1" | |
} else { | |
if (zeros > ones) return "1" | |
else return "0" | |
} | |
} | |
for (let element of arrays) { | |
result += (decision(element, gamma_epsilon)); | |
} | |
return parseInt(result, 2); | |
} | |
const powerConsumption = countResult(inputArray, "gamma") * countResult(inputArray, "epsilon"); | |
console.log(powerConsumption); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment