-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path7.ts
53 lines (44 loc) · 1.27 KB
/
7.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 * as fs from "fs";
const input = fs.readFileSync("7-input.txt", "utf8");
// const input = `190: 10 19
// 3267: 81 40 27
// 83: 17 5
// 156: 15 6
// 7290: 6 8 6 15
// 161011: 16 10 13
// 192: 17 8 14
// 21037: 9 7 18 13
// 292: 11 6 16 20`;
const lines = input.split("\n");
const solution = (isPart2: boolean) => {
function dfs(target: number, cur: number, nums: number[]): boolean {
if (cur > target) {
return false;
}
if (nums.length === 0) {
if (cur === target) {
return true;
}
return false;
}
const nextNum = nums.at(0)!;
const r1 = dfs(target, cur * nextNum, nums.slice(1));
const r2 = dfs(target, cur + nextNum, nums.slice(1));
const r3 = isPart2 ? dfs(target, Number(`${cur}${nextNum}`), nums.slice(1)) : false;
return r1 || r2 || r3;
}
let total = 0;
for (const line of lines) {
const target = Number(line.split(":")[0]);
const nums = line
.split(": ")[1]
.split(" ")
.map((x) => Number(x));
if (dfs(target, nums[0], nums.slice(1))) {
total += target;
}
}
return total;
};
console.log(solution(false));
console.log(solution(true));