diff --git a/2024/01/2024-01.run.xml b/2024/01/2024-01.run.xml new file mode 100644 index 0000000..e673453 --- /dev/null +++ b/2024/01/2024-01.run.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/2024/01/index.test.ts b/2024/01/index.test.ts new file mode 100644 index 0000000..03368d8 --- /dev/null +++ b/2024/01/index.test.ts @@ -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); + }); +}); diff --git a/2024/01/index.ts b/2024/01/index.ts new file mode 100644 index 0000000..4f32ea1 --- /dev/null +++ b/2024/01/index.ts @@ -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); +} diff --git a/2024/01/run.ts b/2024/01/run.ts new file mode 100644 index 0000000..88783cd --- /dev/null +++ b/2024/01/run.ts @@ -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);