Kristina Bressler
Kristina Bressler

Reputation: 1732

JS: Nested loops to get diagonal rows and columns?

I'm a bit confused by my attempt to get a diagonal array from nested loops.

Imagine that there's a chessboard that's 8 by 8 squares and there is a queen in one of those squares. I can compute the queen's possible moves up, right, down, and left perfectly, but I'm stuck on the diagonal moves.

Suppose that the queen is on [4, 4] ([row, column]). I wrote this code to generate/loop through the possible diagonal moves, for example, down left.

The r_q is the queen's position on the row of the chessboard (from bottom to up) while the c_q is the queen's position on the column of the chessboard (from left to right).

let dlArr = [];
let attackCount = 0;
let r_q = 4, c_q = 4;

for(let dl = r_q - 1; dl > 0; dl--) {
  for(let ld = c_q - 1; ld > 0; ld--) {
    dlArr.push([dl, ld]);
    attackCount++;
  }
}

console.log(dlArr);

I got back the array for dlArr

[ [ 3, 3 ], [ 3, 2 ], [ 3, 1 ], [ 2, 3 ], [ 2, 2 ], [ 2, 1 ], [ 1, 3 ], [ 1, 2 ], [ 1, 1 ] ]

instead of what it should be

[ [ 3, 3 ], [ 2, 2 ], [ 1, 1 ] ]

What did I do wrong in this nested loops I wrote?

All I can see is that it loops through the first loop before going to the second loop....

Upvotes: 1

Views: 514

Answers (2)

Sappy B.
Sappy B.

Reputation: 38

Your undesired output is returning every permutation of the correct squares because you nested two for loops. Instead, just use a single for loop that decrements each coordinate. This should give you all the squares diagonally Southwest of the Queen:

let dlArr = [];
let attackCount = 0;

let r_q = 4;
let c_q = 4;

let dl = (r_q - 1);
let ld = (c_q - 1);

while (dl > 0 && ld > 0) {
    dlArr.push([dl, ld]);
    attackCount++;
    dl--;
    ld--;
}

console.log(dlArr);

dl doesn't need to be equivalent to ld. There are many positions where this is not the case.


Edit: I thought this shorthand version was funny:

let dlArr = [];
let attackCount = 0;

let r_q = 4;
let c_q = 4;

let dl = r_q; // no need for (r_q - 1)
let ld = c_q; // ditto

while ( (--dl && --ld) > 0 ) {
    dlArr.push([dl, ld]);
    attackCount++;
}

console.log(dlArr);

Upvotes: 1

Asaf
Asaf

Reputation: 1564

You need to check if the same slope is between 2 dots:

if(r_q-c_q === dl-ld)

So:

[4,4],[3,3] 4-4 === 3-3
[4,4],[3,2] 4-4 !== 3-2

let dlArr = [];
let attackCount = 0;
let r_q = 4, c_q = 4;

for(let dl = r_q - 1; dl > 0; dl--) {
  for(let ld = c_q - 1; ld > 0; ld--) {
    if(r_q-c_q === dl-ld){
      dlArr.push([dl, ld]);
      attackCount++;
    }
  }
}

console.log(dlArr);

Upvotes: 0

Related Questions