From 51ca5db42e4208ec94f262895c87d950605a213a Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Tue, 9 Dec 2025 19:44:31 +0100 Subject: [PATCH] 2025 day 9 part 2 in TS --- 2025/day09/README.md | 14 ++++++++++++++ 2025/day09/solve.ts | 45 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 3 deletions(-) create mode 100644 2025/day09/README.md diff --git a/2025/day09/README.md b/2025/day09/README.md new file mode 100644 index 0000000..e159cad --- /dev/null +++ b/2025/day09/README.md @@ -0,0 +1,14 @@ +# Day 9: Typescript + +Lost a lot of time on a swapped argument order. Oh well, such is life. The `package.json` exists to +instruct the interpreter on how to execute the file and doesn't otherwise include any meaningful +dependencies. Everything works with the standard library for Node. + +`ts-node` is used for just-in-time Typescript compilation. You can also compile the file manually +first, then run it as JS. Also, Oracle, please release the name Javascript. + +```console +$ ./solve.ts sample.txt +Part 1: 50 +Part 2: 24 +``` diff --git a/2025/day09/solve.ts b/2025/day09/solve.ts index 70008d3..b6cfdb4 100755 --- a/2025/day09/solve.ts +++ b/2025/day09/solve.ts @@ -26,14 +26,53 @@ const points = lines.map(line => { }); let max_size = 0; +let max_size_contained = 0; + +function has_intersection(left: number, right: number, bottom: number, top: number): boolean { + for (let i = 0; i < points.length; ++i) { + const first = points[i]; + const second = points[(i + 1) % points.length]; + + if (first.x == second.x) { + const yMin = Math.min(first.y, second.y); + const yMax = Math.max(first.y, second.y); + + if (left < first.x && first.x < right && (yMin <= bottom && bottom < yMax || yMin < top && top <= yMax)) { + return true; + } + } else if (first.y == second.y) { + const xMin = Math.min(first.x, second.x); + const xMax = Math.max(first.x, second.x); + + if (bottom < first.y && first.y < top && (xMin <= left && left < xMax || xMin < right && right <= xMax)) { + return true; + } + } else { + throw "Invalid input"; + } + } + return false; +} for (let i = 0; i < points.length; ++i) { for (let j = i + 1; j < points.length; ++j) { - const width = Math.abs(points[i].x - points[j].x) + 1; - const height = Math.abs(points[i].y - points[j].y) + 1; + const left = Math.min(points[i].x, points[j].x); + const right = Math.max(points[i].x, points[j].x); + const bottom = Math.min(points[i].y, points[j].y); + const top = Math.max(points[i].y, points[j].y); - max_size = Math.max(max_size, width * height); + const width = right - left + 1; + const height = top - bottom + 1; + + const area = width * height; + + max_size = Math.max(max_size, area); + if (area > max_size_contained && !has_intersection(left, right, bottom, top)) { + max_size_contained = area; + } } } console.log("Part 1:", max_size); +// Too high: 4531758980 +console.log("Part 2:", max_size_contained);