Skip to content

Commit 0094da9

Browse files
committed
Working part two
1 parent eaa2b24 commit 0094da9

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

2024/7/part-two.ts

+55
Original file line numberDiff line numberDiff line change
@@ -1 +1,56 @@
11
import { input } from './input';
2+
import G from 'generatorics';
3+
4+
interface Equation {
5+
result: number;
6+
numbers: number[];
7+
}
8+
type MULT = '*';
9+
type SUM = '+';
10+
type CONCAT = '||';
11+
type OPS = MULT | SUM | CONCAT;
12+
13+
const VALID_OPERATIONS = ['*', '+', '||'] as const satisfies Array<OPS>;
14+
15+
function evaluate(numbers: number[], operations: Array<OPS>) {
16+
let result = -1;
17+
for (let i = 0; i < numbers.length - 1; i++) {
18+
let a = i === 0 ? numbers[i] : result;
19+
let b = numbers[i + 1];
20+
let op = operations[i];
21+
22+
if (op === '*') {
23+
result = a * b;
24+
} else if (op === '+') {
25+
result = a + b;
26+
} else {
27+
// op === '||'
28+
result = parseInt(`${a}${b}`, 10);
29+
}
30+
}
31+
32+
return result;
33+
}
34+
35+
function couldBeTrue({ result, numbers }: Equation): boolean {
36+
// It is OK to fill with the same reference
37+
const spaces: Array<typeof VALID_OPERATIONS> = Array(numbers.length - 1).fill(VALID_OPERATIONS);
38+
39+
for (const operations of G.cartesian(...spaces)) {
40+
const evaluation = evaluate(numbers, operations);
41+
if (evaluation === result) {
42+
return true;
43+
}
44+
}
45+
46+
return false;
47+
}
48+
49+
let sum = 0;
50+
for (let equation of input) {
51+
if (couldBeTrue(equation)) {
52+
sum += equation.result;
53+
}
54+
}
55+
56+
console.log(sum);

0 commit comments

Comments
 (0)