Solve 2024-02

This commit is contained in:
2024-12-02 13:07:13 +01:00
parent 503001220d
commit 8e1060e6a4
4 changed files with 79 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="2024-02" type="BunRunConfiguration">
<option name="program" value="2024/02/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';
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);
});
});
+43
View File
@@ -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;
}
+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);