diff --git a/day20.ts b/day20.ts index 0352e79..caba620 100644 --- a/day20.ts +++ b/day20.ts @@ -1,11 +1,14 @@ -import { PointSet } from './lib/rect.ts'; +import { Counter } from './lib/counter.ts'; import { AllDirs, Point, PointMap, Rect } from './lib/rect.ts'; import { type MainArgs, parseFile } from './lib/utils.ts'; import { BinaryHeap } from '@std/data-structures'; type Parsed = string[][]; -function astar(r: Rect, start: Point, end: Point): PointSet { +function astar(r: Rect): Point[] { + const [start] = r.filter((v) => v === 'S'); + const [end] = r.filter((v) => v === 'E'); + const gScore = new PointMap([[start, 0]]); const fScore = new PointMap([[start, 0]]); const prev = new PointMap(); @@ -19,10 +22,10 @@ function astar(r: Rect, start: Point, end: Point): PointSet { const g = gScore.get(p)!; if (p.equals(end)) { - const ps = new PointSet(); + const ps: Point[] = []; let n: Point | undefined = end; while (n) { - ps.add(n); + ps.push(n); n = prev.get(n); } return ps; @@ -42,68 +45,50 @@ function astar(r: Rect, start: Point, end: Point): PointSet { } } - return new PointSet(); + return []; } -function part1(inp: Parsed): number { - const r = new Rect(inp); - const [start] = r.filter((v) => v === 'S'); - const [end] = r.filter((v) => v === 'E'); - - const ps = astar(r, start, end); - const pss = ps.size; - const target = pss - 100; +function part1(ps: Point[]): number { + const pslen = ps.length; let tot = 0; - let pcount = 0; - for (const p of ps) { - let qcount = 0; - for (const q of ps) { - if (p.equals(q)) { - continue; - } + + for (let pcount = 0; pcount < pslen; pcount++) { + const p = ps[pcount]; + for (let qcount = pcount + 2; qcount < pslen; qcount++) { + const q = ps[qcount]; const d = p.manhattan(q); if (d === 2) { - if ((pcount + (pss - qcount) + 1) <= target) { + if ((pcount + d - qcount - 1) <= -100) { tot++; } } - qcount++; } - pcount++; } return tot; } -function part2(inp: Parsed): number { - const r = new Rect(inp); - const [start] = r.filter((v) => v === 'S'); - const [end] = r.filter((v) => v === 'E'); - - const ps = astar(r, start, end); - const pss = ps.size; - const target = pss - 100; +function part2(ps: Point[]): number { + const pslen = ps.length; let tot = 0; - let pcount = 0; - for (const p of ps) { - let qcount = 0; - for (const q of ps) { - if (p.equals(q)) { - continue; - } + for (let pcount = 0; pcount < pslen; pcount++) { + const p = ps[pcount]; + for (let qcount = pcount + 2; qcount < pslen; qcount++) { + const q = ps[qcount]; const d = p.manhattan(q); - if (d <= 20) { - if ((pcount + (pss - qcount) + d - 1) <= target) { + if ((d > 1) && (d <= 20)) { + if ((pcount + d - qcount - 1) <= -100) { tot++; } } - qcount++; } - pcount++; } return tot; } export default async function main(args: MainArgs): Promise<[number, number]> { const inp = await parseFile(args); - return [part1(inp), part2(inp)]; + const r = new Rect(inp); + const ps = astar(r); + + return [part1(ps), part2(ps)]; }