@@ -28,11 +28,15 @@ type GuardPosition = {
28
28
const startY = map . findIndex ( ( row ) => row . includes ( GUARD_STARTING_CHAR ) ) ;
29
29
const startX = map [ startY ] . indexOf ( GUARD_STARTING_CHAR ) ;
30
30
31
- const getVisitedCells = (
32
- mapInput : typeof map ,
33
- keyFormatter : ( guardPos : GuardPosition ) => string = ( { x, y } ) => `${ x } ,${ y } ` ,
34
- enableLoopDetection = false
35
- ) => {
31
+ const getVisitedCells = ( {
32
+ enableLoopDetection,
33
+ keyFormatter = ( { x, y } ) => `${ x } ,${ y } ` ,
34
+ mapInput,
35
+ } : {
36
+ enableLoopDetection ?: boolean ;
37
+ keyFormatter ?: ( guardPos : GuardPosition ) => string ;
38
+ mapInput : typeof map ;
39
+ } ) => {
36
40
let guardPosition : GuardPosition = { x : startX , y : startY , direction : "UP" } ;
37
41
let loopDetected = false ;
38
42
@@ -42,8 +46,8 @@ const getVisitedCells = (
42
46
while ( true ) {
43
47
const nextMove = DIRECTIONS [ guardPosition . direction ] ;
44
48
const nextPosition = {
45
- x : Math . abs ( guardPosition . x + nextMove . x ) ,
46
- y : Math . abs ( guardPosition . y + nextMove . y ) ,
49
+ x : guardPosition . x + nextMove . x ,
50
+ y : guardPosition . y + nextMove . y ,
47
51
} ;
48
52
49
53
if (
@@ -87,8 +91,41 @@ const getVisitedCells = (
87
91
( ( ) => {
88
92
console . time ( "part 1" ) ;
89
93
90
- const { visitedCells } = getVisitedCells ( map ) ;
94
+ const { visitedCells } = getVisitedCells ( { mapInput : map } ) ;
91
95
92
96
console . log ( "part 1 visitedCells count ::" , visitedCells . size ) ;
93
97
console . timeEnd ( "part 1" ) ;
94
98
} ) ( ) ;
99
+
100
+ // Part 2
101
+ ( ( ) => {
102
+ console . time ( "part 2" ) ;
103
+
104
+ const { visitedCells } = getVisitedCells ( { mapInput : map } ) ;
105
+ let loopsFound = 0 ;
106
+
107
+ for ( let visitedCell of visitedCells ) {
108
+ const [ x , y ] = visitedCell . split ( "," ) . map ( ( n ) => parseInt ( n ) ) ;
109
+
110
+ if ( x === startX && y === startY ) {
111
+ continue ;
112
+ }
113
+
114
+ const mapClone = JSON . parse ( JSON . stringify ( map ) ) as typeof map ;
115
+ mapClone [ y ] [ x ] = OBSTACLE_CHAR ;
116
+
117
+ const { loopDetected } = getVisitedCells ( {
118
+ enableLoopDetection : true ,
119
+ keyFormatter : ( guardPos ) =>
120
+ `${ guardPos . x } ,${ guardPos . y } ,${ guardPos . direction } ` ,
121
+ mapInput : mapClone ,
122
+ } ) ;
123
+
124
+ if ( loopDetected ) {
125
+ loopsFound += 1 ;
126
+ }
127
+ }
128
+
129
+ console . log ( "part 2 loopsFound ::" , loopsFound ) ;
130
+ console . timeEnd ( "part 2" ) ;
131
+ } ) ( ) ;
0 commit comments