1+ /**
2+ * @author MadhavBahlMD
3+ * @date 25/01/2019
4+ * Method - First Assign then place values
5+ * Complexity - O(row*col) // row and col are the number of rows and number of columns
6+ */
7+
8+ function makeMineField ( posArr , row , col ) {
9+ let mineField = [ ] ;
10+
11+ // initialize the mineField with zeros
12+ for ( let i = 0 ; i < row ; i ++ ) {
13+ let thisRow = [ ] ;
14+ for ( let j = 0 ; j < col ; j ++ )
15+ thisRow . push ( 0 ) ;
16+ mineField . push ( thisRow ) ;
17+ }
18+
19+ // Iterate over position array and put -1 at those positions in the minefield
20+ for ( let pos of posArr ) {
21+ mineField [ pos [ 0 ] ] [ pos [ 1 ] ] = - 1 ;
22+ }
23+
24+ // Iterate over each element and complete the mine field
25+ for ( let i = 0 ; i < row ; i ++ ) {
26+ for ( let j = 0 ; j < col ; j ++ ) {
27+ if ( mineField [ i ] [ j ] !== - 1 )
28+ mineField [ i ] [ j ] = assignValue ( mineField , i , j , row , col ) ;
29+ }
30+ }
31+
32+ console . log ( mineField ) ;
33+ }
34+
35+ function assignValue ( mineField , thisRow , thisCol , row , col ) {
36+ let count = 0 ;
37+
38+ // Check for bombs in all 3 rows
39+ for ( let i = - 1 ; i <= 1 ; i ++ )
40+ for ( let j = - 1 ; j <= 1 ; j ++ )
41+ if ( ( thisRow + i >= 0 && thisRow + i < row ) && ( thisCol + j >= 0 && thisCol + j < col ) )
42+ if ( mineField [ thisRow + i ] [ thisCol + j ] === - 1 ) count ++ ;
43+
44+ return count ;
45+ }
46+
47+ makeMineField ( [ [ 0 , 0 ] , [ 0 , 1 ] ] , 4 , 4 ) ;
0 commit comments