The assignment: Write a function that returns a list of the diagonal elements in a square grid.
function getDiagonal(grid, whichDiagonal)
The diagonals are named by the constants at the top of the program.
var DIAGONAL_TOP_LEFT_BOTTOM_RIGHT = 0;
var DIAGONAL_BOTTOM_LEFT_TOP_RIGHT = 1;
For example, given the grid grid with these contents:
4 2 5
1 8 3
7 3 9
The call of getDiagonal(grid, DIAGONAL_TOP_LEFT_BOTTOM_RIGHT) should return an array with contents:
[4, 8, 9]
Now test your function by calling it several times, and printing out the grid.
My code prints ", , ," and I'm not sure why here is my full code:
var DIAGONAL_TOP_LEFT_BOTTOM_RIGHT = 0;
var DIAGONAL_BOTTOM_LEFT_TOP_RIGHT = 1;
function start(){
var grid = new Grid(3, 3);
grid.initFromArray([
["4", "2", "5"],
["1", "8", "3"],
["7", "3", "9"]
]);
getDiagonal(grid, DIAGONAL_TOP_LEFT_BOTTOM_RIGHT);
}
function getDiagonal(grid, whichDiagonal){
var diagonalList = [];
for(var row = 0; row<grid.numRows() + 1; row++){
for(var col = 0; col<grid.numCols() + 1; col++){
if(row == col){
var curr = grid.get[row, col];
diagonalList.push(curr);
}
}
}
println(diagonalList);
}
I'm also not sure how to use the 2 given variables at the top
there are two problems in your code in this function:
function getDiagonal(grid, whichDiagonal){
var diagonalList = [];
for(var row = 0; row<grid.numRows() + 1; row++){
for(var col = 0; col<grid.numCols() + 1; col++){
if(row == col){
var curr = grid.get[row, col];
diagonalList.push(curr);
}
}
}
println(diagonalList);
}
Change it to this:
function getDiagonal(grid, whichDiagonal){
var diagonalList = [];
for(var row = 0; row<grid.numRows(); row++){
for(var col = 0; col<grid.numCols(); col++){
if(row == col){
var curr = grid.get(row, col);
diagonalList.push(curr);
}
}
}
println(diagonalList);
}