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

Time:01-04

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:

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

CodePudding user response:

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]] 

CodePudding user response:

You could check the indices and check the logical not value and return a number of the check.

function createGrid(m, n) {
    return Array.from(
        { length: m },
        (_, i) => Array.from(
            { length: n },
            (_, j) =>  (!i !== !j)
        )
    );
};

createGrid(3, 4).map(a => console.log(...a))

  •  Tags:  
  • Related