Skip to content

Commit

Permalink
add day 9 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Laniman committed Dec 9, 2023
1 parent 8b5d5fe commit dfa728f
Show file tree
Hide file tree
Showing 5 changed files with 311 additions and 0 deletions.
53 changes: 53 additions & 0 deletions 09/a.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { expect, test } from "bun:test";

function solution(input: string) {
const sequences = input.split("\n").map((line) => line.split(" ").map(Number));

let ans = 0;

for (const sequence of sequences) {
const acc = [sequence];

let last = acc[acc.length - 1];
while (!last.every((el) => el === 0)) {
const next = [];
for (let i = 1; i < last.length; i++) {
const el = last[i] - last[i - 1];
next.push(el);
}
acc.push(next);
last = next;
}

const acc1 = acc.map((el) => el[el.length - 1]);
const acc2 = [0];

for (let i = acc1.length - 2; i >= 0; i--) {
const next = acc1[i] + acc2[acc2.length - 1];
acc2.push(next);
}

ans += acc2[acc2.length - 1];
}

return ans;
}

test("example", async () => {
const file = Bun.file(`${import.meta.dir}/example.txt`);
const input = await file.text();

const actual = solution(input);
const expected = 114;
expect(actual).toBe(expected);
});

test("puzzle input", async () => {
const file = Bun.file(`${import.meta.dir}/input.txt`);
const input = await file.text();

const actual = solution(input);
const expected = 1702218515;

expect(actual).toBe(expected);
});
53 changes: 53 additions & 0 deletions 09/b.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { expect, test } from "bun:test";

function solution(input: string) {
const sequences = input.split("\n").map((line) => line.split(" ").map(Number));

let ans = 0;

for (const sequence of sequences) {
const acc = [sequence];

let last = acc[acc.length - 1];
while (!last.every((el) => el === 0)) {
const next = [];
for (let i = 1; i < last.length; i++) {
const el = last[i] - last[i - 1];
next.push(el);
}
acc.push(next);
last = next;
}

const acc1 = acc.map((el) => el[0]);
const acc2 = [0];

for (let i = acc1.length - 2; i >= 0; i--) {
const next = acc1[i] - acc2[acc2.length - 1];
acc2.push(next);
}

ans += acc2[acc2.length - 1];
}

return ans;
}

test("example", async () => {
const file = Bun.file(`${import.meta.dir}/example.txt`);
const input = await file.text();

const actual = solution(input);
const expected = 2;
expect(actual).toBe(expected);
});

test("puzzle input", async () => {
const file = Bun.file(`${import.meta.dir}/input.txt`);
const input = await file.text();

const actual = solution(input);
const expected = 925;

expect(actual).toBe(expected);
});
3 changes: 3 additions & 0 deletions 09/example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
Loading

0 comments on commit dfa728f

Please sign in to comment.