Skip to content

Commit

Permalink
wip: d7 p2
Browse files Browse the repository at this point in the history
  • Loading branch information
wiktoriavh committed Dec 7, 2024
1 parent 3336922 commit c148e3d
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
41 changes: 40 additions & 1 deletion src/7.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type Operator = "+" | "*";
type Operator = "+" | "*" | "||";

function solution(input: string): { part1: string; part2: string } {
let result1 = 0;
Expand All @@ -17,11 +17,19 @@ function solution(input: string): { part1: string; part2: string } {
number
>();

const correctResults2 = new Map<
ReturnType<typeof crypto.randomUUID>,
number
>();

lines.forEach((line) => {
const { result, nums } = line;
const id = crypto.randomUUID();

function calculate(alpha: number, beta: number, operator: Operator) {
if (operator == "||") {
return Number(`${alpha}${beta}`);
}
return eval(`${alpha} ${operator} ${beta}`);
}

Expand All @@ -46,12 +54,43 @@ function solution(input: string): { part1: string; part2: string } {
};

foo(nums[0], nums[1], 1);

const bar = (a: number, b: number, index: number) => {
if (index === nums.length) {
return;
}
console.log(a, b, index);

const alpha = calculate(a, b, "+");
const beta = calculate(a, b, "*");
const gamma = calculate(a, b, "||");

if (alpha === result && index === nums.length - 1) {
correctResults2.set(id, alpha);
return;
} else if (beta === result && index === nums.length - 1) {
correctResults2.set(id, beta);
return;
} else if (gamma === result && index === nums.length - 1) {
correctResults2.set(id, gamma);
return;
} else {
bar(alpha, nums[index + 1], index + 1);
bar(beta, nums[index + 1], index + 1);
bar(gamma, nums[index + 1], index + 1);
}
};

bar(nums[0], nums[1], 1);
});

const sum = (acc: number, curr: number) => acc + curr;
const values = Array.from(correctResults.values());
result1 = values.reduce(sum, 0);

const values2 = Array.from(correctResults2.values());
result2 = values2.reduce(sum, 0);

return {
part1: result1.toString(),
part2: result2.toString(),
Expand Down
2 changes: 1 addition & 1 deletion test/7.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const EXAMPLE_1 = `190: 10 19
const RESULT_1 = "3749";

const EXAMPLE_2 = EXAMPLE_1;
const RESULT_2 = "0";
const RESULT_2 = "11387";

describe("Day 7", () => {
test("Part 1", () => {
Expand Down

0 comments on commit c148e3d

Please sign in to comment.