Skip to content

Commit 3b6f576

Browse files
committed
AoC2025: day 5 part 2
1 parent a96403a commit 3b6f576

2 files changed

Lines changed: 10 additions & 48 deletions

File tree

2024-2025/src/2025/day05/day05.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ describe('2025 Day 5', () => {
88

99
test('Part 2', async () => {
1010
expect(await part2('testInput1')).toEqual(14);
11-
expect(await part2('input')).toEqual(1111);
11+
expect(await part2('input')).toEqual(345821388687084);
1212
});
1313
});

2024-2025/src/2025/day05/day05.ts

Lines changed: 9 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -46,55 +46,17 @@ function findFreshIngredients(idRanges: IdRange[], ingredientIds: number[]): num
4646
}
4747

4848
function findTotalFreshIngredientCount(idRanges: IdRange[], _: number[]): number {
49-
let reduceRanges = true;
50-
let idRangesCopy = idRanges.slice();
49+
const sorted = idRanges.slice().sort((a, b) => a.from - b.from);
50+
const merged: IdRange[] = [];
5151

52-
while (reduceRanges) {
53-
reduceRanges = false;
54-
for (let i = 0; i < idRanges.length; i++){
55-
const a = idRanges[i];
56-
for (let j = i + 1; j < idRanges.length; j++) {
57-
const b = idRanges[j];
58-
59-
if (a.from >= b.from && a.from <= b.to) {
60-
reduceRanges = true;
61-
idRangesCopy.splice(j, 1);
62-
idRangesCopy.splice(i, 1);
63-
if (a.to >= b.to) {
64-
idRangesCopy.push({ from: b.from, to: a.to });
65-
}
66-
if (b.to >= a.to) {
67-
idRangesCopy.push({ from: b.from, to: b.to });
68-
}
69-
break;
70-
}
71-
72-
if (a.to >= b.from && a.to <= b.to) {
73-
reduceRanges = true;
74-
idRangesCopy.splice(j, 1);
75-
idRangesCopy.splice(i, 1);
76-
77-
if (a.from >= b.from) {
78-
idRangesCopy.push({ from: b.from, to: b.to });
79-
}
80-
if (b.from >= a.from) {
81-
idRangesCopy.push({ from: a.from, to: b.to });
82-
}
83-
break;
84-
}
85-
}
86-
if (reduceRanges) {
87-
break;
88-
}
52+
for (const range of sorted) {
53+
const last = merged[merged.length - 1];
54+
if (last && range.from <= last.to + 1) {
55+
last.to = Math.max(last.to, range.to);
56+
} else {
57+
merged.push({ ...range });
8958
}
90-
91-
idRanges = idRangesCopy.slice();
9259
}
9360

94-
let freshCount = 0;
95-
idRanges.forEach(idRange => {
96-
freshCount += (idRange.to - idRange.from) + 1;
97-
})
98-
99-
return freshCount;
61+
return merged.reduce((sum, r) => sum + (r.to - r.from + 1), 0);
10062
}

0 commit comments

Comments
 (0)