-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday19.ts
53 lines (42 loc) · 1.27 KB
/
day19.ts
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
import type { Day } from './Day.ts';
export class DayImpl implements Day {
private readonly input: { patterns: string[][]; towels: string[][] };
constructor(input: string) {
this.input = this.parseInput(input);
}
parseInput(input: string) {
const [patterns, towels] = input
.trim()
.split('\n\n');
return {
patterns: patterns.split(', ').map(v => v.split('')),
towels: towels.split('\n').map(l => l.split('')),
};
}
partOne() {
const { patterns, towels } = this.input;
return towels.filter(towel => combinations(towel, patterns) > 0).length;
}
partTwo() {
const { patterns, towels } = this.input;
return towels.reduce((a, towel) => a + combinations(towel, patterns), 0);
}
}
function combinations(towel: string[], patterns: string[][]) {
const memo: Record<number, number> = {};
const recur = (pos: number) => {
if (memo[pos] !== undefined)
return memo[pos];
if (pos === towel.length)
return 1;
const matches = patterns
.filter((p) => {
return p.every((pv, i) => towel[pos + i] !== undefined && towel[pos + i] === pv);
});
let result = 0;
matches.forEach(p => result += recur(pos + p.length));
memo[pos] = result;
return result;
};
return recur(0);
}