-
Notifications
You must be signed in to change notification settings - Fork 0
/
12.mjs
59 lines (50 loc) · 1.38 KB
/
12.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { readInput } from "./utils.mjs";
const input = readInput(import.meta);
const memoize = (fn) => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (!(key in cache)) {
cache[key] = fn(...args);
}
return cache[key];
};
};
const getPossibleCombinations = memoize((line, constraints) => {
if (!line.length) {
return !constraints.length ? 1 : 0;
}
if (!constraints.length) {
return line.includes("#") ? 0 : 1;
}
if (line[0] === "#") {
const [constraint, ...newConstraints] = constraints;
const match = line.match(
new RegExp(`^[#?]{${constraint}}([.?]\\.*(.*)|$)`),
);
if (!match) {
return 0;
}
return getPossibleCombinations(match[2] ?? "", newConstraints);
}
return (
getPossibleCombinations("#" + line.slice(1), constraints) +
getPossibleCombinations(line.replace(/\?[.]*/, ""), constraints)
);
});
const solve = (input, repeats) => {
let result = 0;
for (const inputLine of input.split("\n")) {
const [p1, p2] = inputLine.split(" ");
const line = `${p1}?`.repeat(repeats).slice(0, -1).replace(/^\.+/, "");
const constraints = `${p2},`
.repeat(repeats)
.slice(0, -1)
.split(",")
.map(Number);
result += getPossibleCombinations(line, constraints);
}
return result;
};
console.log(solve(input, 1));
console.log(solve(input, 5));