Unable to iterate over a 2D array using 'rows' in JavaScript or TypeScript

Imagine I need to generate a 2D array with this specific structure:

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

To achieve this, I first initialized a 2D array with 0 values:

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

    return 0;
};

Next, I updated the values in the first row (except for grid[0][0]) to be 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 attempted to update the values in the first column (excluding 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;
};

Unfortunately, an error is thrown stating:

grid[i] is undefined

I'm confused about what might be causing this. Any explanations would be greatly appreciated.

TypeScript Playground Code Link

Answer №1

Two mistakes have been identified:

  • You mistakenly switched m and n values instead of filling with 1.
  • An overflow was created by using the condition i <=, when it should have been i <.

Here is the corrected version:

function calculatePaths(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;
};

calculatePaths(3, 4);

Result:

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

Answer №2

To validate the indices and evaluate the logical not value, you can create a function that returns a specific number based on the check.

function generateGrid(x, y) {
    return Array.from(
        { length: x },
        (_, i) => Array.from(
            { length: y },
            (_, j) => +(!i !== !j)
        )
    );
};

generateGrid(3, 4).map(row => console.log(...row))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating with Nokia Here maps: plotting a path using GPS coordinates

I am currently developing a GPS tracking system and my goal is to visually represent the device's locations as a route. The challenge I'm facing is that there is a REST API available for this purpose, but my client-side application relies on soc ...

Is there a way to retrieve the ID from a span and convert it into a string format?

let wordSpan = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>' console.log(wordSpan.id); console.log(wordSpan.attr('id')); console.log(wordSpan.getAttribute('id')); let newDiv = document.c ...

eliminating identical items in an array

I've been working on finding and removing duplicate objects in an array, but I keep encountering an error when trying to access the filterList[i+1].tagID element. Strangely, manually inputting the [i+1] values seems to yield the correct results. I&apo ...

Upon attempting to send a POST request with PostgreSQL, the following error is displayed: "Invalid input syntax for type integer: '12 Pro'"

I encountered an error while attempting to send a POST request using PostgreSQL/Sequelize. Can anyone help me identify the issue in this code? async create(req, res, next) { try { let { name, price, brandId, typeId, info } = req.body; c ...

Tips for creating unit tests for my Angular service that utilizes the mergeMap() function?

As a beginner with the karma/jasmine framework, I am currently exploring how to add a test case for my service method shown below: public getAllChassis(): Observable<Chassis[]> { return this.http.get('chassis').pipe( merge ...

Pinia has not been instantiated yet due to an incorrect sequence of JavaScript file execution within Vue.js

I'm currently developing a Vue.js application using Vite, and I have a Pinia store that I want to monitor. Below is the content of my store.js file: import { defineStore } from 'pinia'; const useStore = defineStore('store', { st ...

When executing the release command in Ionic 3, the Angular AoT build encountered a failure

Struggling to get my Sony Z2 smartphone app running. Command used: ionic build android --prod --release Error displayed in console: typescript error Type CirckelmovementPage in C:/Users/fearcoder/Documents/natuurkundeformules/src/pages/cir ...

Tips for preserving the contents of a list with HTML and Javascript

My latest project involves creating a website with a To-Do list feature. Users should be able to add and delete items from the list, which I achieved using JavaScript. Now, my next goal is to ensure that the current items on the list are saved when the pag ...

managing the focus and blur events within an Angular 1.5 component

While working on an angular js project recently, I encountered a situation involving handling focus and blur events in a textbox. My specific scenario required adding the $ sign when focus is lost from the textbox and removing it when the textbox is focuse ...

External script implementing StratifiedJSIt is possible for an external script

Recently, I stumbled upon the amazing StratifiedJS library that offers many features I find essential. It functions flawlessly when implemented directly in my HTML file, like so: <script src="libraries/stratified.js"></script> <scr ...

Angular SPA boasting an impressive one million pages

Currently, I am in the process of transitioning my webshop, which contains numerous products, to an Angular SPA application using ngRoute and HTML5 mode. I have come up with a method where I receive some of my routes from the server as a JSON object, but s ...

Extract the element from one array that is not present in another array

I am attempting to extract the values from arrayOne that do not appear in both groups within arrayTwo. In the example below, I am looking to identify b and d for group1 and a and b for group2. arrayOne = ['a','b','c',' ...

Angular - Automatically create thumbnails for uploaded images and videos

I am working on an Angular application that allows users to upload files. My goal is to create thumbnail images for uploaded images and videos without saving them locally. Instead, I plan to pass them along with the original file data to another API. Howev ...

Unable to show pop-up upon clicking

My goal is to create a popup that appears when the 'Propose' button is clicked. TestPopUp.tsx const TestPopUp = () => { return ( <div> <p>TEST</p> </div> ); }; export default TestPopUp; CandidateActi ...

Building a class structure with a JavaScript MVC approach - best practices

I am looking to develop a JavaScript web application using the MVC-like principle. While my code is functional, I am facing challenges in implementing it correctly. I have created a global variable called APP where I store controllers, views, and other com ...

Issue with React's MaterialUI Select Component not displaying the values passed as props

In my component, I have a FormControl element that includes a Select element accepting an array of options for MenuItem options, as well as a value as props. The component code looks like this: const TaxonomySelector = (props) => { const { isDisabled, t ...

Executing a dual ajax request in Angular 5

I am attempting to perform two HTTP requests consecutively, with the second request depending on the result of the first. However, it seems like I am overlooking something: getParkingSpots(date) { var gmt = this.getTimezone().subscribe(data=>{ if(d ...

Regular expressions are functioning as expected in the debugger tool, but they are not working

I am trying to retrieve all the content from a text file until the first empty line appears. Although I have found a successful regex, I am facing issues when attempting to achieve the same outcome in Javascript. (loading the file's contents is func ...

Implementing CSS styles with jQuery

Looking for a way to dynamically add CSS attributes to different form elements like text fields, text areas, checkboxes, and dropdowns? There's also a separate block that lists possible CSS properties such as font, font-style, width, and padding. What ...

What differences exist in the implications of the options for the socket.io server object?

According to the socket.io documentation, you have the option to utilize the http.Server object or directly input a port number into the socket.io server object. What distinguishes the two methods? Instantiate the socket.io Object const io = require(&apo ...