@@ -6,7 +6,8 @@ const dirs = { '^': [0, -1, '>'], 'v': [0, 1, '<'], '<': [-1, 0, '^'], '>': [1,
6
6
const findPosAndDir = ( map ) => map . flatMap ( ( r , y ) => r . flatMap ( ( c , x ) => dirs [ c ] ? [ x , y , c ] : null ) . filter ( p => p !== null ) ) ;
7
7
const outOfBounds = ( map , x , y ) => x < 0 || x > map [ 0 ] . length - 1 || y < 0 || y > map . length - 1 ;
8
8
9
- const patrol = ( map , x , y , dir ) => {
9
+ const patrol = ( map , obs ) => {
10
+ let [ x , y , dir ] = findPosAndDir ( map ) ;
10
11
const route = [ ] ;
11
12
while ( true ) {
12
13
const posAndDir = `${ x } ,${ y } ${ dir } ` ;
@@ -15,24 +16,22 @@ const patrol = (map, x, y, dir) => {
15
16
const [ dx , dy , rotate ] = dirs [ dir ] ;
16
17
const [ nx , ny ] = [ x + dx , y + dy ] ;
17
18
if ( outOfBounds ( map , nx , ny ) ) return route ;
18
- if ( map [ ny ] [ nx ] == '#' ) dir = rotate ;
19
+ if ( map [ ny ] [ nx ] == '#' || ( obs ?. x == nx && obs ?. y == ny ) ) dir = rotate ;
19
20
else [ x , y ] = [ nx , ny ] ;
20
21
}
21
22
}
22
23
23
- const [ startx , starty , startdir ] = findPosAndDir ( map ) ;
24
- const route = patrol ( map , startx , starty , startdir ) ;
24
+ const route = patrol ( map ) ;
25
25
const positions = route . map ( posAndDir => posAndDir . split ( ' ' ) [ 0 ] ) ;
26
26
const uniqPositions = [ ...new Set ( positions ) ] ;
27
27
console . log ( `day6a: ${ uniqPositions . length } ` ) ;
28
28
29
+ const firstPosition = positions [ 0 ] ;
29
30
// try adding obstacle to visited position on route and check for loop
30
31
const loop = uniqPositions . filter ( pos => {
32
+ if ( pos == firstPosition ) return false ; // not allowed to add obstacle to start
31
33
const [ x , y ] = pos . split ( ',' ) . map ( Number ) ;
32
- if ( x == startx && y == starty ) return false ; // not allowed to add obstacle to start
33
- const nmap = JSON . parse ( JSON . stringify ( map ) ) ; // deep clone
34
- nmap [ y ] [ x ] = '#' ; // add new obstacle
35
- return patrol ( nmap , startx , starty , startdir ) == null ; //
34
+ return patrol ( map , { x, y} ) == null ; // patrol returns null in case of loop
36
35
} ) ;
37
36
const uniqLoop = new Set ( loop ) ;
38
37
console . log ( `day6b: ${ uniqLoop . size } ` ) ;
0 commit comments