Skip to content

Commit

Permalink
day 02 (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
spalberg authored Dec 2, 2024
1 parent 0ce47f3 commit 11b403f
Show file tree
Hide file tree
Showing 5 changed files with 1,060 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .vscode/days.code-snippets
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"}",
"",
"if (import.meta.main) {",
" console.log(part1(loadInput($1)));",
" console.log(part2(loadInput($1)));",
" console.log(part1(await loadInput($1)));",
" console.log(part2(await loadInput($1)));",
"}"
],
"description": "implementation for daily challenge"
Expand Down
38 changes: 38 additions & 0 deletions days/02/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { loadInput } from "utils";

export function part1(input: Array<string>) {
const reports = parseReports(input);
const safeReports = reports.filter(isReportSafe);
return safeReports.length;
}

export function part2(input: Array<string>) {
const reports = parseReports(input);
const safeReports = reports.filter((r) =>
isReportSafe(r) || isDampenedReportSafe(r)
);
return safeReports.length;
}

function parseReports(input: Array<string>) {
return input.map((l) => l.split(" ").map(Number));
}

function isReportSafe(report: Array<number>) {
if (report.length < 2) return true;
const direction = report[0] - report[1] > 0 ? -1 : 1;
for (let i = 1; i < report.length; i += 1) {
const diff = (report[i - 1] - report[i]) * -direction;
if (diff < 1 || diff > 3) return false;
}
return true;
}

function isDampenedReportSafe(report: Array<number>) {
return report.map((_, i) => report.toSpliced(i, 1)).some(isReportSafe);
}

if (import.meta.main) {
console.log(part1(await loadInput(2)));
console.log(part2(await loadInput(2)));
}
19 changes: 19 additions & 0 deletions days/02/main_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { expect } from "@std/expect";
import { part1, part2 } from "./main.ts";

const input = [
"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",
];

Deno.test("part 1", () => {
expect(part1(input)).toBe(2);
});

Deno.test("part 2", () => {
expect(part2(input)).toBe(4);
});
2 changes: 1 addition & 1 deletion days/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ type Solution = { part1: PartFunction; part2: PartFunction };

const days: Record<string, Solution> = {};

for (const day of [1]) {
for (const day of [1, 2]) {
days[pad(day)] = await import(`./${pad(day)}/main.ts`);
}

Expand Down
Loading

0 comments on commit 11b403f

Please sign in to comment.