Search code examples
c++arraysmultidimensional-arraychess

C++ Print diagonal in two dimensional array using one point as reference


I have a two dimensional array which represents a chess board - t[8][8] Now let's say we have a queen on that game at t[4][7]

How to draw the diagonals using this queen reference's coordinate ?

What I have already tried:

  • 2 nested for loop starting at xQueen position and yQueen position for the second loop with conditions like if (i == (xQueen - i) && j == (yQueen - j))
  • Same but starting at 1 to 8
  • Using a while loop until the limit of the board is reached

How to locate at any point on the board if it's in the diagonal of the queen ?

Thank you


Solution

  • Let's number the array so that it starts from 0.

    Say you have a queen at (4, 7). You might find that the position you were to find include (3, 6), (2, 5) and (5, 6).

    Draw them out on the paper, and you'll find it clear that what you wanted is quite simple.

    If the queen is at position (x, y), then all the positions (i, j) with (i + j == x + y || i - j == x - y are the answer. To make it clearer, you might want to represent each position (i, j) with i + j, and put them in the matrix. You'll find that the positions on the same diagonal have the same result. This fact is the same if you represent (i, j) with i - j.