Skip to content

Commit 24f1504

Browse files
committed
refactor
1 parent 19dd000 commit 24f1504

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

src/2025/day10.js

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,5 @@
11
import { memoize } from "../utils/memoize.js";
2-
3-
function* product(arrays) {
4-
if (arrays.length === 0) yield [];
5-
else {
6-
let [head, ...tail] = arrays;
7-
for (let item of head) {
8-
for (let rest of product(tail)) yield [item, ...rest];
9-
}
10-
}
11-
}
2+
import { powerSet } from "combinatorial-generators";
123

134
function parse(input) {
145
return input.split("\n").map(line => {
@@ -22,12 +13,12 @@ function parse(input) {
2213

2314
function producePatterns(buttons, length) {
2415
let patterns = {};
25-
for (let pressed of product(Array(buttons.length).fill([0, 1]))) {
26-
let lights = Array(length).fill(0);
27-
for (let i = 0; i < pressed.length; i++) {
28-
if (pressed[i]) for (let j of buttons[i]) lights[j] = lights[j] ? 0 : 1;
16+
for (let pressed of powerSet(buttons.map((_, i) => i))) {
17+
let lights = Array(length).fill(false);
18+
for (let i of pressed) {
19+
for (let j of buttons[i]) lights[j] = !lights[j];
2920
}
30-
let key = lights.join("");
21+
let key = lights.map(x => (x ? 1 : 0)).join("");
3122
patterns[key] = [...(patterns[key] || []), pressed];
3223
}
3324
return patterns;
@@ -38,8 +29,7 @@ export function part1(input) {
3829
let p1 = 0;
3930
for (let { indicator, buttons } of machines) {
4031
let patterns = producePatterns(buttons, indicator.length);
41-
let sums = patterns[indicator].map(x => x.reduce((a, b) => a + b, 0));
42-
p1 += Math.min(...sums);
32+
p1 += Math.min(...patterns[indicator].map(x => x.length));
4333
}
4434
return p1;
4535
}
@@ -57,12 +47,9 @@ export function part2(input) {
5747
let options = patterns[target.map(x => x % 2).join("")] || [];
5848
for (let pressed of options) {
5949
let jolt = Array(jolts.length).fill(0);
60-
for (let i = 0; i < pressed.length; i++) {
61-
if (pressed[i]) for (let j of buttons[i]) jolt[j] += pressed[i];
62-
}
50+
for (let i of pressed) for (let j of buttons[i]) jolt[j]++;
6351
let newTarget = jolt.map((a, i) => (target[i] - a) / 2);
64-
let sum = pressed.reduce((a, b) => a + b, 0);
65-
total = Math.min(total, sum + 2 * presses(newTarget));
52+
total = Math.min(total, pressed.length + 2 * presses(newTarget));
6653
}
6754
return total;
6855
});

0 commit comments

Comments
 (0)