From 69f0bf3f1c50c10d3e57e652812dce6c66e912e5 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Sun, 18 Dec 2022 11:57:22 -0500 Subject: [PATCH] faster part 1 --- 2022/15/part1.js | 55 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 8 deletions(-) diff --git a/2022/15/part1.js b/2022/15/part1.js index 64861c7..72190fd 100644 --- a/2022/15/part1.js +++ b/2022/15/part1.js @@ -1,8 +1,10 @@ import * as R from "remeda"; +import { passthru } from "../08/part1.js"; import { readFile } from "../05/part1.js"; import V from '@yanick/vyktor'; +import { createLogger } from "vite"; const readInput = (...args) => R.pipe( @@ -18,7 +20,38 @@ const readInput = (...args) => export const puzzleInput = readInput(import.meta.url, "input"); export const sample = readInput(import.meta.url, "sample"); -export const unbeaconAtLine = targetLine => R.createPipe( +/** @returns [number,number][] */ +const mergeRanges = ( ranges ) => + ranges.reduce( (accum,range) => { + if( accum.length === 0 ) return [ range ]; + if( R.last( accum )[1] < range[0] ) { + accum.push(range); + } + else { + R.last(accum)[1] = Math.max( + R.last(accum)[1], range[1] + ) + } + return accum; + }, [] ); + +const spy = passthru( x => console.log(x) ); + +const entriesInRange = (targetLine,entries) => { + + entries = R.uniqBy(entries.map(([_,beacon])=>beacon).filter( beacon => beacon?.y === targetLine ), (x) => x.toString()); + + console.log(entries); + + return range => { + return entries.filter( + entry => (entry.x >= range[0]) && (entry.x <= range[1]) + ).length + } +}; + +export const unbeaconAtLine = targetLine => entries => R.pipe( + entries, R.map( ([x,y]) => [ x, x.manhattanDistance(y) ] ), R.filter( e => ( @@ -30,15 +63,21 @@ e => ( e => { const l = e[1] - Math.abs(targetLine - e[0].y); - return R.range( + return [ e[0].x - l, - e[0].x + l, - ) } + e[0].x + l ] + } ), - R.flatten, - R.uniq, - x => x.length - + spy, + (ranges) => + ranges.sort( (a,b) => { + return (a[0] - b[0]) || (a[1]-b[1]); + } ) + , + spy, + mergeRanges, + spy, + R.sumBy( range => range[1] - range[0] + 1 - entriesInRange(targetLine,entries)(range) ) ); export default unbeaconAtLine(2000000);