1- function countSides ( walls ) {
2- let sides = 0 ;
3- walls . forEach ( cells => {
4- const points = [ ...cells ] . sort ( ( a , b ) => a - b ) ;
5- for ( let i = 0 ; i < points . length ; i ++ ) {
6- if ( points [ i ] + 1 !== points [ i + 1 ] ) sides ++ ;
7- }
8- } ) ;
9- return sides ;
10- }
11-
121function walk ( map , x , y ) {
132 const queue = [ { x, y } ] ;
143 const cells = new Set ( [ `${ x } ,${ y } ` ] ) ;
154 const walls = new Map ( ) ;
16- let perimeter = 0 ;
175 while ( queue . length > 0 ) {
186 const p = queue . shift ( ) ;
197 const neighbors = [
@@ -29,7 +17,6 @@ function walk(map, x, y) {
2917 queue . push ( o ) ;
3018 }
3119 } else {
32- perimeter ++ ;
3320 if ( o . x === p . x ) {
3421 const wall = `h,${ p . y } ,${ o . y } ` ;
3522 walls . set ( wall , ( walls . get ( wall ) || new Set ( ) ) . add ( p . x ) ) ;
@@ -40,25 +27,46 @@ function walk(map, x, y) {
4027 }
4128 } ) ;
4229 }
43- return { cells, perimeter , sides : countSides ( walls ) } ;
30+ return { cells, walls } ;
4431}
4532
46- export function part1 ( input , part2 = false ) {
33+ function forEachRegion ( input , fn ) {
4734 const map = input . split ( "\n" ) . map ( line => line . split ( "" ) ) ;
4835 let visited = new Set ( ) ;
49- let sum = 0 ;
5036 for ( let y = 0 ; y < map . length ; y ++ ) {
5137 for ( let x = 0 ; x < map [ y ] . length ; x ++ ) {
5238 if ( visited . has ( `${ x } ,${ y } ` ) ) continue ;
53- const { cells, perimeter , sides } = walk ( map , x , y ) ;
39+ const { cells, walls } = walk ( map , x , y ) ;
5440 visited = visited . union ( cells ) ;
55- if ( ! part2 ) sum += cells . size * perimeter ;
56- else sum += cells . size * sides ;
41+ fn ( cells , walls ) ;
5742 }
5843 }
44+ }
45+
46+ function countSides ( walls ) {
47+ let sides = 0 ;
48+ walls . forEach ( cells => {
49+ const points = [ ...cells ] . sort ( ( a , b ) => a - b ) ;
50+ for ( let i = 0 ; i < points . length ; i ++ ) {
51+ if ( points [ i ] + 1 !== points [ i + 1 ] ) sides ++ ;
52+ }
53+ } ) ;
54+ return sides ;
55+ }
56+
57+ export function part1 ( input ) {
58+ let sum = 0 ;
59+ forEachRegion ( input , ( cells , walls ) => {
60+ let perimeter = walls . values ( ) . reduce ( ( acc , set ) => acc + set . size , 0 ) ;
61+ sum += cells . size * perimeter ;
62+ } ) ;
5963 return sum ;
6064}
6165
6266export function part2 ( input ) {
63- return part1 ( input , true ) ;
67+ let sum = 0 ;
68+ forEachRegion ( input , ( cells , walls ) => {
69+ sum += cells . size * countSides ( walls ) ;
70+ } ) ;
71+ return sum ;
6472}
0 commit comments