1

I have a 2D array like this:

const matrix = [
  [0, 0, 0, 0],
  [0, 2, 1, 0],
  [0, 1, 2, 0],
  [0, 0, 0, 0]
]

If the x and y of a cell is given, for example 2 and 1 (matrix[2][1] is 1), how can I find all diagonal lines (two arrays, each of which contain the points of every cell in the diagonal in proper order) which pass through the provided cell? The matrix (array) will always be symmetrical and square (To be exact, I have an 8x8 grid).

Example:

const matrix = [
  [0, 0, 0, 0],
  [0, 2, 1, 0],
  [0, 1, 2, 0],
  [0, 0, 0, 0]
];

const cellX = 2, cellY = 1;

// Code ...

const diagonalFromTopLeft = [0, 1, 0];
const diagonalFromTopRight = [0, 1, 1, 0]

Bonus points if you are able to find every line, not just the diagonals (vertical and horizontal, but I can figure that out myself).

5
  • I assume the input matrix isn't always symmetrical, right?
    – yunzen
    Apr 26, 2021 at 9:28
  • Additionally, are the input matrices always square?
    – yunzen
    Apr 26, 2021 at 9:30
  • @yunzen they are always symmetrical and square, though they will be bigger. To be exact I will have an 8x8 grid. Apr 26, 2021 at 9:34
  • @trincot both are 0-based. I fixed the question Apr 26, 2021 at 9:38
  • Yeah @trincot. Thanks for pointing that out. I fixed it Apr 26, 2021 at 9:39

1 Answer 1

3

You could iterate the rows (and corresponding index) and calculate the corresponding x coordinate on the two diagonals. When they are within range, the corresponding values can be added to the relevant array:

function diagonals(matrix, cellX, cellY) {
    let forward = []; // diagonal according forward slash shape: / 
    let backward = []; // diagonal according backslash shape: \
    let n = matrix.length;
    matrix.forEach((row, y) => {
        let x = cellX - (cellY - y);
        if (x >= 0 && x < n) backward.push(row[x]);
        x = cellX + (cellY - y);
        if (x >= 0 && x < n) forward.push(row[x]); 
    });
    return [forward, backward];
}


const matrix = [
  [0, 0, 0, 0],
  [0, 2, 1, 0],
  [0, 1, 2, 0],
  [0, 0, 0, 0]
];

const cellX = 2, cellY = 1;

console.log(diagonals(matrix, cellX, cellY));

3
  • It works! Though I'll have to read through that math to find out how though ;) Apr 26, 2021 at 9:44
  • It looks like forward is actually backward here. Apr 26, 2021 at 9:45
  • 1
    Yes, it depends how you call them. I used backward like in "backward slash" (\), and forward like in "forward slash" (/)
    – trincot
    Apr 26, 2021 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.