Solve 2024-01
This commit is contained in:
@@ -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>
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
Reference in New Issue
Block a user