Printing diagonal Array

I mean, I think at this point it is worth pointing out that you don’t need nested loops to solve this. What @admit8490 is saying is correct, but I think it’s building on a bad premise. If you want to solve it with the code you have, that’s fine. It’s probably a good idea just for understanding.

But you are using two, nested loops when all you really need is one loop. For the L2R diagonal, that is trivial. Borrowing from @admit8490 's good advice, list out the coordinates you need. Can you see how to get those with a single loop? What is the relationship between the two coordinates?

For the R2L do the same thing. Generating the second coordinate would be a tiny bit harder, not by much, and would involve a tiny bit of math. What is the relationship between the two coordinates?

1 Like

I completely agree with that.
Also I think it’s worth mentioning, that:

if single loop will be used properly, there will be no need for the if statement

1 Like

Basically, my plan is to get just one line direction using one nested loop, which I got right. I was able to print the right diagonal from just one loop, but could not print the left diagonal with one loop. the L-diagonal should be (0,3)(1,2)(2,1)(1,3), but i couldn’t make it work

not quite right I think. (1,3) is not the coordinate you want here

(3,0) it was a mistake

More hints:
to get the right formula, you may wanna use board.length

for (let i = 0; i < board.length; i++) {
newArray.push(board[i][i]);
}

this print R-diagonal using one loop

1 Like

Well, for L-diagonal, you need to change the second [i]. You have pattern for coordinates, you should be able to build the formula you need.

2 Likes