Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't loop through 2D array using 'rows' in JS or TS

Suppose, I want to create a 2D array of the following structure:

[0, 1, 1, 1]
[1, 0, 0, 0]
[1, 0, 0, 0]

For achieving my goal, at first, I created a 2D array with initial values of 0:

function createGrid(m: number, n: number): number {
    let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));

    return 0;
};

Then, I changed the values of the first row (except grid[0][0]) to 1:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function uniquePaths(m: number, n: number): number {
    let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));

    for (let i = 1; i <= m; i++) {
        grid[0][i] = 1;
    }

    return 0;
};

Similarly, I tried to change the values of the first column (except grid[0][0]) to 1:

function uniquePaths(m: number, n: number): number {
    let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));

    for (let i = 1; i <= m; i++) {
        grid[0][i] = 1;
    }

    for (let i = 1; i <= n; i++) {
        grid[i][0] = 1;   // <<-- 'Throws error here`
    }

    return 0;
};

But, it throws the following error:

grid[i] is undefined

Can someone please explain what I’m missing here?

TypeScript Playground Code Link

>Solution :

There is two errors:

  • You swapped m and n when you wanted to fill with 1.
  • You created overflow with condition i <=, you needed i <.

Corrected version:

function uniquePaths(m: number, n: number): number {
    let grid: number[][] = new Array(m).fill(0).map(() => new Array(n).fill(0));

    for (let i = 1; i < n; i++) {
        grid[0][i] = 1;
    }

    for (let i = 1; i < m; i++) {
        grid[i][0] = 1;
    }

    console.log(grid);

    return 0;
};

uniquePaths(3, 4);

Result:

[[0, 1, 1, 1],
 [1, 0, 0, 0],
 [1, 0, 0, 0]] 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading