Created
December 10, 2022 22:23
-
-
Save 0916dhkim/6c0fc71caa616ee8a5f4ade5b71b730b to your computer and use it in GitHub Desktop.
Advent of Code - Day 3
This file contains hidden or 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
const { readFile } = require("fs/promises"); | |
function isUppercase(letter) { | |
return letter.toLowerCase() !== letter; | |
} | |
const alphaVal = (s) => s.toLowerCase().charCodeAt(0) - 97 + 1; | |
function letterToPriority(letter) { | |
return alphaVal(letter) + (isUppercase(letter) ? 26 : 0); | |
} | |
function findCommonLetter(threeLines) { | |
for (const letter of threeLines[0]) { | |
const inSecondLine = threeLines[1].includes(letter); | |
const inThirdLine = threeLines[2].includes(letter); | |
if (inSecondLine && inThirdLine) { | |
return letter; | |
} | |
} | |
} | |
function parseRawInput(rawInput) { | |
const lines = rawInput.split("\n"); | |
let i = 0; | |
const groupOfThrees = []; | |
let currentGroup; | |
for (const line of lines) { | |
if (i % 3 === 0) { | |
currentGroup = []; | |
groupOfThrees.push(currentGroup); | |
} | |
currentGroup.push(line); | |
i++; | |
} | |
return groupOfThrees.map((group) => | |
letterToPriority(findCommonLetter(group)) | |
); | |
} | |
async function step2() { | |
const path = "./input.txt"; | |
const content = await readFile(path, { encoding: "utf-8" }); | |
const rucksack = parseRawInput(content); | |
const sum = rucksack.reduce((a, b) => a + b, 0); | |
console.log(sum); | |
} | |
step2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment