Solve 2024-01

This commit is contained in:
2024-12-01 14:10:47 +01:00
parent 3cb015b230
commit c41848f336
4 changed files with 77 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="2024-01" type="BunRunConfiguration">
<option name="program" value="2024/01/run.ts" />
<option name="workingDirectory" value="$PROJECT_DIR$" />
<method v="2" />
</configuration>
</component>
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'bun:test';
import { solveFirst, solveSecond } from './index.ts';
const testInput = `3 4
4 3
2 5
1 3
3 9
3 3`;
describe('2024-01', () => {
it('first', () => {
expect(solveFirst(testInput)).toBe(11);
});
it('second', () => {
expect(solveSecond(testInput)).toBe(31);
});
});
+41
View File
@@ -0,0 +1,41 @@
import { groupBy, sumArray } from '../../utils/array.ts';
function splitColumnList(input: string) {
const regex = /^(\d*) {3}(\d*)$/gm;
const match = input.matchAll(regex);
const [first, second] = Array.from(
match,
(m) => [Number(m[1]), Number(m[2])] as [number, number]
).reduce<[number[], number[]]>(
([listA, listB], [a, b]) => {
listA.push(a);
listB.push(b);
return [listA, listB];
},
[[], []]
);
return { first, second };
}
export function solveFirst(input: string): number {
const { first, second } = splitColumnList(input);
first.sort();
second.sort();
const pairs = first.map((e, i) => Math.abs(e - second[i]));
return sumArray(pairs);
}
export function solveSecond(input: string): number {
const { first, second } = splitColumnList(input);
const right = groupBy(second, (e) => e);
const score = first.map(
(e) => e * (right.find((r) => r.key === e)?.elements?.length || 0)
);
return sumArray(score);
}
+12
View File
@@ -0,0 +1,12 @@
import { join } from 'path';
import { solveFirst, solveSecond } from './index.ts';
const input = await Bun.file(join(__dirname, 'input.txt')).text();
const firstAnswer = solveFirst(input);
console.log(firstAnswer);
const secondAnswer = solveSecond(input);
console.log(secondAnswer);