2022 Day 3 Part 2

This commit is contained in:
Sven Weidauer 2022-12-03 09:19:46 +01:00
parent bae91ea042
commit f15c8ea362

View file

@ -11,6 +11,19 @@ function calculate_score(input) {
} }
} }
function find_badge(group) {
const first = group.shift();
const sets = group.map(item => new Set(item));
for (const character of first) {
if (sets.find(item => !item.has(character)) === undefined) {
return character;
}
}
throw 'No badge found';
}
async function puzzle() { async function puzzle() {
const lines = readline.createInterface({ const lines = readline.createInterface({
@ -18,6 +31,9 @@ async function puzzle() {
}); });
var score = 0; var score = 0;
var badge_score = 0;
var group = [];
for await (const line of lines) { for await (const line of lines) {
const mid = line.length / 2; const mid = line.length / 2;
const first = line.substring(0, mid); const first = line.substring(0, mid);
@ -29,8 +45,16 @@ async function puzzle() {
break; break;
} }
} }
group.push(line);
if (group.length == 3) {
badge_score += calculate_score(find_badge(group));
group = [];
}
} }
console.log(`Part 1: Score ${score}`); console.log(`Part 1: Score ${score}`);
console.log(`Part 2: Score ${badge_score}`);
} }
puzzle(); puzzle();