Created
December 5, 2022 01:53
-
-
Save LordSmurf/17a916fbd3fca90b4b533e19bce7de24 to your computer and use it in GitHub Desktop.
AOC 2022 - Day 3
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
const fs = require("fs/promises"); | |
const mainInput = "input.txt"; | |
const example = "example.txt"; | |
const example2 = "example2.txt"; | |
async function readInput(fileName) { | |
const file = await fs.readFile(fileName, "utf-8"); | |
return file.trim().replace(/\r/g, "").split("\n"); | |
} | |
const priorities = { | |
a: 1, | |
b: 2, | |
c: 3, | |
d: 4, | |
e: 5, | |
f: 6, | |
g: 7, | |
h: 8, | |
i: 9, | |
j: 10, | |
k: 11, | |
l: 12, | |
m: 13, | |
n: 14, | |
o: 15, | |
p: 16, | |
q: 17, | |
r: 18, | |
s: 19, | |
t: 20, | |
u: 21, | |
v: 22, | |
w: 23, | |
x: 24, | |
y: 25, | |
z: 26, | |
A: 27, | |
B: 28, | |
C: 29, | |
D: 30, | |
E: 31, | |
F: 32, | |
G: 33, | |
H: 34, | |
I: 35, | |
J: 36, | |
K: 37, | |
L: 38, | |
M: 39, | |
N: 40, | |
O: 41, | |
P: 42, | |
Q: 43, | |
R: 44, | |
S: 45, | |
T: 46, | |
U: 47, | |
V: 48, | |
W: 49, | |
X: 50, | |
Y: 51, | |
Z: 52, | |
}; | |
async function solveFirst(fileName) { | |
const inputs = await readInput(fileName); | |
let prioSum = 0; | |
inputs.forEach((ruck, idx) => { | |
let compartments = [ | |
ruck.substring(0, ruck.length / 2), | |
ruck.substring(ruck.length / 2), | |
]; | |
//console.log(`====================\nRuck: ${idx}\nCompartments: ${compartments}\n====================`); | |
let items1 = compartments[0].split(""); | |
let items2 = compartments[1].split(""); | |
let sharedItem = items1.filter((i1) => items2.some((i2) => i1 === i2)); | |
prioSum += priorities[sharedItem[0]]; | |
}); | |
return prioSum; | |
} | |
async function solveTwo(fileName) { | |
const file = await readInput(fileName); | |
const groups = []; | |
let group = []; | |
let prioSum = 0; | |
for (const line of file) { | |
group.push(line); | |
if (group.length === 3) { | |
groups.push(group); | |
group = []; | |
} | |
} | |
groups.forEach((group) => { | |
let items1 = group[0].split(""); | |
let items2 = group[1].split(""); | |
let items3 = group[2].split(""); | |
let sharedItem = items1.filter( | |
(i1) => items2.some((i2) => i1 === i2) && items3.some((i3) => i1 === i3) | |
); | |
prioSum += priorities[sharedItem[0]]; | |
}); | |
return prioSum; | |
} | |
(async () => { | |
const partOne = await solveFirst(mainInput); | |
const partTwo = await solveTwo(mainInput); | |
console.log(partOne); | |
console.log(partTwo); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment