From 8e1060e6a43f5f1820f6f884a819f54b0c3f8283 Mon Sep 17 00:00:00 2001 From: Pascal Syma Date: Mon, 2 Dec 2024 13:07:13 +0100 Subject: [PATCH] Solve 2024-02 --- 2024/02/2024-02.run.xml | 7 +++++++ 2024/02/index.test.ts | 17 ++++++++++++++++ 2024/02/index.ts | 43 +++++++++++++++++++++++++++++++++++++++++ 2024/02/run.ts | 12 ++++++++++++ 4 files changed, 79 insertions(+) create mode 100644 2024/02/2024-02.run.xml create mode 100644 2024/02/index.test.ts create mode 100644 2024/02/index.ts create mode 100644 2024/02/run.ts diff --git a/2024/02/2024-02.run.xml b/2024/02/2024-02.run.xml new file mode 100644 index 0000000..50f5096 --- /dev/null +++ b/2024/02/2024-02.run.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/2024/02/index.test.ts b/2024/02/index.test.ts new file mode 100644 index 0000000..9137dfd --- /dev/null +++ b/2024/02/index.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'bun:test'; +import { solveFirst, solveSecond } from './index.ts'; + +describe('2024-02', () => { + const testInput = `7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9`; + it('first', () => { + expect(solveFirst(testInput)).toBe(2); + }); + it('second', () => { + expect(solveSecond(testInput)).toBe(4); + }); +}); diff --git a/2024/02/index.ts b/2024/02/index.ts new file mode 100644 index 0000000..b5c06fa --- /dev/null +++ b/2024/02/index.ts @@ -0,0 +1,43 @@ +const isSafe = (numbers: number[]) => { + const increasing = numbers[1] - numbers[0]; + + for (let i = 1; i < numbers.length; i++) { + const signedDiff = numbers[i] - numbers[i - 1]; + if (signedDiff < 0 !== increasing < 0) { + return false; + } + + const diff = Math.abs(signedDiff); + if (diff < 1 || diff > 3) { + return false; + } + } + + return true; +}; + +export function solveFirst(input: string): number { + const lines = input.split('\n').map((line) => line.split(' ').map(Number)); + + return lines.filter(isSafe).length; +} + +export function solveSecond(input: string): number { + const lines = input.split('\n').map((line) => line.split(' ').map(Number)); + + const safe = lines.filter((numbers) => { + if (isSafe(numbers)) { + return true; + } + + for (let i = 0; i < numbers.length; i++) { + if (isSafe(numbers.toSpliced(i, 1))) { + return true; + } + } + + return false; + }); + + return safe.length; +} diff --git a/2024/02/run.ts b/2024/02/run.ts new file mode 100644 index 0000000..88783cd --- /dev/null +++ b/2024/02/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);