Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
Codehs grid diagonally

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!