Drawing coordinate lines on a two-dimensional array that simulates a grid

Are you solving a challenging code problem from the advent of code series? Check out the problem description here.

The task involves processing input data in the form of coordinate lines on a grid (x1,y1 -> x2,y2). The goal is to populate a 2D array with these lines and count the overlapping coordinates. However, there seems to be an issue in my code where only some valid lines are added to the grid despite all being identified correctly. Here's a snippet of what I have so far:

import { stdout } from 'process';

function getPuzzleInput(fileName : string) : [any[], number, number] {
    const fs = require('fs')
    let coordLines = [];
    let maxX = 0;
    let maxY = 0;

    try {
        const data : string = fs.readFileSync(fileName, 'utf8')
        const lines = data.split("\n");
        let insertIndex = 0;
        for (let lineNum=0; lineNum < lines.length; lineNum++)  {
            let coords : string[] = lines[lineNum].split(" -> ");
            let x1 : number = parseInt(coords[0].split(",")[0].trim());
            let y1 : number = parseInt(coords[0].split(",")[1].trim());
            let x2 : number = parseInt(coords[1].split(",")[0].trim());
            let y2 : number = parseInt(coords[1].split(",")[1].trim());

            if (x1 == x2 || y1 == y2) {
                coordLines.push({x1: x1, y1: y1, x2: x2, y2: y2});
                maxX = Math.max(maxX, x1, x2);
                maxY = Math.max(maxY, y1, y2);
            }
        }
    } catch (err) {
        console.error(err)
    }
    return [coordLines, maxX, maxY];
}

function getSolutionOne(coordLines, maxX : number, maxY : number) : void {
    let grid = [];
    for (let y = 0; y <= maxY; y++) {
        grid[y] = [];
        for (let x = 0; x <= maxX; x++) {
            grid[y][x] = 0;
        }
    }
    // Rest of the code remains unchanged
}
// Main function call remains same

main();

The output generated by this code shows that not all expected lines are being added to the grid. The actual solution should look different based on the correct lines to be added. Can you spot why certain lines are not being included as they should?

Answer №1

In some cases, x2 or y2 may be smaller than x1 or y1, and your current code does not take that into consideration - the loops you are using currently are

for (let y = line.y1; y <= line.y2; y++) {
, which will not run at all if the second value is initially smaller than the first.

You should determine whether the elements are smaller or larger first, or decide on the direction of iteration - whether it's +1 or -1. For example:

const increment = x2 > x1 ? 1 : -1;
for (let x = line.x1; x !== line.x2; x += increment) {
    grid[line.y1][x]++;
}

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

Verify whether a component is a React.ReactElement<any> instance within a child mapping operation

I am facing a challenge with a component that loops through children and wraps them in a div. I want to exclude certain elements from this process, but I am struggling to determine if the child is a ReactElement or not (React.ReactChild can be a string or ...

Incorporating an external SVG file into an Angular project and enhancing a particular SVG element within the SVG with an Angular Material Tooltip, all from a TypeScript file

Parts of the angular code that are specific |SVG File| <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="950" height="450" viewBox="0 0 1280.000000 1119.000000" preserveAspectRatio= ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

How to minimize xAxes labels in Chart.js

As a newcomer to Chart.js, I am encountering some challenges. My goal is to create a bar chart that displays hourly information. However, when attempting to show data for a week, a month, or an extended period, I face issues with reducing the labels on the ...

Tips for reusing a Jest mock for react-router's useHistory

When testing my code, I set up a mock for the useHistory hook from react-router-dom like this: jest.mock("react-router-dom", () => ({ useHistory: () => ({ length: 13, push: jest.fn(), block: jest.fn(), createHref: jest.fn(), go ...

Transform the code provided by bundleMDX into an HTML string specifically for RSS, all the while utilizing the mdx-bundler

I am currently working on developing an RSS reader and I need to convert the code returned by bundleMDX into a string. This is necessary so that I can utilize it with ReactDOMServer.renderToStaticMarkup(mdx) in my project. You can find a similar implement ...

angular2 ngif does not effectively conceal HTML elements when set to false

In the HTML file, I have the following code: <p *ngIf="!checklistsready"> not ready </p> <p *ngIf="checklistsready"> Ready </p> And in my TypeScript file, it looks like this: checklistsready: boolean = false; constructor( ...

Which Angular tools should I be using: map, pipe, or tap?

When my component initializes, I retrieve data from the server import {Rules} from "../../interfaces/interfaces"; rules: Rules ngOnInit() { this.tt = this.rulesService.getUserClientRules().subscribe( t => { console.log(t) con ...

Unable to loop through array generated by service - potential async complication?

In my service, I am populating an array of items by calling a function like this: items: IItem[] = []; ... LoadItems() { this.GetItems().subscribe((res) => { // console.log(res); if (res.status == 200 && res.body. ...

Creating a unique tooltip component for ag-grid with the use of Material tooltips

I am facing an issue with the current angular ag-grid tooltip example, as it is not functioning properly. https://stackblitz.com/edit/angular-ag-grid-tooltip-example-fb7nko Utilizing Javascript/typescript in Angular 8 with the latest ag-grid release. I h ...

What is the best way to find the total number of times a specific key appears within an array using PHP?

I'm currently working with a sample object array that has been JSON decoded and looks like the one below. The values of indexes value1, value2, value3 inside this object array may increase to value'n' in the future. I am looking to obtain th ...

Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type. **template.html** <mat-form-field > <input matInput [matAutocomplete]="auto" [formControl]="customerFi ...

How to only disable checkboxes that are currently checked in Angular 8

click here to view an image**I would like to know how I can disable only the selected/checked items on a p-listbox in Angular 8. Is it possible to achieve this by adding a specific property or using CSS? Currently, when I try to add the [disabled] proper ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...

Creating a Bottom Sliding Menu in Ionic 2

Hey there! I'm working on something that might not fit the typical definition of a sliding menu. It's not for navigation purposes, but rather to house some data. My idea for this actually comes from Apple Maps: https://i.stack.imgur.com/hL1RU.jp ...

Always deemed non-assignable but still recognized as a universal type?

I'm curious about why the never type is allowed as input in generic's extended types. For example: type Pluralize<A extends string> = `${A}s` type Working = Pluralize<'language'> // 'languages' -> Works as e ...

Running a Redux Thunk action from within a TypeScript environment, beyond the confines of a React component

Currently, I am in the process of converting a React Native app into TypeScript. Unfortunately, I have encountered an issue with dispatching thunk actions outside of the store. Below is how my store is configured: store/index.ts import { createStore, app ...

Is it possible to customize error messages in @hapi/joi?

Seeking assistance with custom error message overrides in Joi. Consider the schema outlined below. const joiSchema = Joi.object({ name: Joi.string().required(), email: Joi.string().email().required() }) try{ const schema = joiSchema.validateAsyn ...

Tips for using jest toHaveBeenCalled with multiple instances

Currently, I am in the process of writing a test case for one of my functions. This function calls another function from a library, and I am attempting to mock this function (saveCall). Below is a snippet of the sample code in question: import { Call } fro ...