@ParasArora/

queen's attack II

Nodejs

No description

fork
loading
Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function queensAttack(size, numOfObs, queenRow, queenCol, obstacles) {
  let obsCoords = {};

  obstacles.forEach(([row, col]) => {
    obsCoords[row] = obsCoords[row] || {};
    obsCoords[row][col] = true;
  });

  let directions = [
  //row col
    [-1, 0], // top
    [-1, 1], // top-right
    [ 0, 1], // right
    [ 1, 1], // bottom-right
    [ 1, 0], // bottom
    [ 1,-1], // bottom-left
    [ 0,-1], // left
    [-1,-1], // top-left
  ];

  let counter = 0;

  directions.forEach(([row,col]) => {
    let loc = {
      row: queenRow + row,
      col: queenCol + col
    };
    
    while(loc.row <= size && loc.row > 0 && loc.col <= size && loc.col > 0){

      if(obsCoords[loc.row] && obsCoords[loc.row][loc.col]){
        break;
      }
      counter++;
      loc.row += row;
      loc.col += col;
    }

  })

  return counter;
}

queensAttack(5, 3, 4, 3, [
  [5, 5],
  [4, 2],
  [2, 3]
])
node v10.16.0