Skip to content

Instantly share code, notes, and snippets.

@amiratak88
Last active December 3, 2021 08:05
Show Gist options
  • Save amiratak88/8a6dc534dc5d5754f3221c1962d7ff57 to your computer and use it in GitHub Desktop.
Save amiratak88/8a6dc534dc5d5754f3221c1962d7ff57 to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 3
const lines = `
101000111100
000011111101
011100000100
100100010000
.
.
.
`.trim().split('\n');
function calculateCount(lines) {
const count = [];
lines.forEach((line) => {
Array.from(line).forEach((digit, digitIndex) => {
count[digitIndex] ||= [0, 0];
count[digitIndex][+digit]++;
});
});
return count;
}
const gammaRate = calculateCount(lines)
.map(([zerosCount, onesCount]) => (zerosCount > onesCount ? '0' : '1'))
.join('');
const epsilonRate = calculateCount(lines)
.map(([zerosCount, onesCount]) => (zerosCount > onesCount ? '1' : '0'))
.join('');
const powerConsumption = parseInt(gammaRate, 2) * parseInt(epsilonRate, 2);
function calculateRating(array, shouldKeepLine, digitIndex = 0) {
if (array.length === 1 || digitIndex === array[0].length) return array[array.length - 1];
const count = calculateCount(array);
const newArray = array.filter((line) => shouldKeepLine(line[digitIndex], ...count[digitIndex]));
if (!newArray.length) return array[array.length - 1];
return calculateRating(newArray, shouldKeepLine, digitIndex + 1);
}
const oxygenGeneratorRating = calculateRating(
lines,
(digit, zerosCount, onesCount) => digit === (onesCount >= zerosCount ? '1' : '0')
);
const co2ScrubberRating = calculateRating(
lines,
(digit, zerosCount, onesCount) => digit === (zerosCount <= onesCount ? '0' : '1')
);
const lifeSupportRating = parseInt(oxygenGeneratorRating, 2) * parseInt(co2ScrubberRating, 2);
console.log({ powerConsumption, lifeSupportRating });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment