Lets say we have a grid containing cells, and that we want to return two arrays where each contains all the cells in the diagonal with that cell, up-left to bottom-right and the opposite one. What would be the best way to go about it?
I tried the following in javascript (note that board is a one dimensional array that supposedly represents a square grid with a side length of boardSize. position is the cell which I am trying to find its diagonals.)
var diagonal1 = [];
var diagonal2 = [];
for(var i = 0; i < board.length; i++) {
if (i == position) diagonal.move_index = diagonal.length
if (Math.abs(position - i) % (boardSize + 1) == 0) {
diagonal1.push(board[i]);
}
else if (Math.abs(position - i) % (boardSize - 1) == 0) {
diagonal2.push(board[i]);
}
}
but this is only doing the job for elements that lie in the main diagonal, not others. Any ideas?
Example:
if board = [1,2,3,4,5,6,7,8]
board:
1 2 3
4 5 6
7 8 9
then If I say that I want to find the diagonals for position = 4
I should get:
diagonal1 = [4, 8]
diagonal2 = [2, 4]
and if I choose another position, lets say position = 5, then:
diagonal1 = [1, 3, 5]
diagonal2 = [3, 5, 7]
Does the order of the cells in the diagonals matter? If not, the algorithm in this pseudocode should suffice. If it does matter, you just need to reorder some chunks and play around with the loop variables…