1+ import path from "node:path" ;
2+ import { readInputLineByLine } from "@utils/io" ;
3+ import { Cardinal , Coord , Grid , move , readLinesToGrid } from "@utils/grid" ;
4+
5+ export async function part1 ( inputFile : string ) {
6+ return await day7 ( inputFile , findBeanSplits ) ;
7+ }
8+
9+ export async function part2 ( inputFile : string ) {
10+ return await day7 ( inputFile ) ;
11+ }
12+
13+ async function day7 ( inputFile : string , calcFn ?: ( grid : Grid , initialPos : Coord ) => number ) {
14+ const inputPath = path . join ( __dirname , inputFile ) ;
15+ const lines = await readInputLineByLine ( inputPath ) ;
16+ const { grid, initialPos } = readLinesToGrid ( lines , 'S' ) ;
17+ return calcFn ?.( grid , initialPos ! ) ;
18+ }
19+
20+ function findBeanSplits ( grid : Grid , initialPos : Coord ) : number {
21+ const visited = new Set < string > ( ) ;
22+ const queue : Coord [ ] = [ move ( initialPos , Cardinal . SOUTH ) ] ;
23+ let splits = 0 ;
24+
25+ while ( queue . length > 0 ) {
26+ let current = queue . shift ( ) ! ;
27+
28+ while ( true ) {
29+ const key = current . serialize ( ) ;
30+ const cellValue = grid . get ( key ) ;
31+
32+ if ( cellValue === undefined || visited . has ( key ) ) break ;
33+
34+ visited . add ( key ) ;
35+
36+ if ( cellValue === '^' ) {
37+ splits ++ ;
38+ const left = move ( current , Cardinal . WEST ) ;
39+ const right = move ( current , Cardinal . EAST ) ;
40+ if ( grid . has ( left . serialize ( ) ) )
41+ queue . push ( left ) ;
42+ if ( grid . has ( right . serialize ( ) ) )
43+ queue . push ( right ) ;
44+ break ;
45+ }
46+
47+ current = move ( current , Cardinal . SOUTH ) ;
48+ }
49+ }
50+
51+ return splits ;
52+ }
0 commit comments