JavaScript: Modifying an Array of Matrices

Could anyone assist me with updating a matrix array? I have an initial matrix with preset values and need to update specific coordinates within it.

Here is the base matrix:

var myMatrix = [
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-'],
    ['-','-','-','-','-','-','-','-','-','-']
];

I managed to update certain points in the matrix, resulting in:

----x-----
-----x----
--------x-
--------x-
---x------
----------
-------x--
----------
----x-----
-------x--

This was done using the following function:

function stepTwo(coordinates) {
    console.log('Step Two');
    for(var j =0; j < coordinates.length; j ++) {
        myMatrix[coordinates[j].y][coordinates[j].x] = 'x';
    }
    for(var i = 0; i < myMatrix.length; i++) {
        console.log(myMatrix[i].join(' '));
    }
}

var coordinatesArray = [
    {x: 4, y: 0},
    {x: 5, y: 1},
    {x: 8, y: 2},
    {x: 8, y: 3},
    {x: 3, y: 4},
    {x: 7, y: 6},
    {x: 4, y: 8},
    {x: 7, y: 9},
];

stepTwo(coordinatesArray);

Now I am looking to create another function that updates the matrix like this:

xxxxx-----
xxxxxx----
xxxxxxxxx-
xxxxxxxxx-
xxxx------
----------
xxxxxxxx--
----------
xxxxx-----
xxxxxxxx--

The new function should take in a row and convert a specified number of '-'s to 'x's.

For reference, here is a JSFiddle link showcasing my current progress (looking for help specifically with "stepThree"): https://jsfiddle.net/2vbd27f0/73/

Thank you in advance for any assistance provided!

Answer №1

Here is my approach to the problem - generating a new array of x's based on the specified number and appending the remaining elements (fiddle):

function updateArray(numbers) {
    numbers.forEach(function(item) {
        var line = exampleMatrix[item.y];

        if(!line) { // If there is no line, proceed to the next iteration
            return;
        }

        var fillNumber = item.x > line.length ? line.length : item.x; // Use length if fill number exceeds line length

        exampleMatrix[item.y] = new Array(fillNumber + 1) // Create an array slightly larger than the fill number
            .join('x') // Fill it with x's to get the correct count
            .split('') // Split it to create a new array
            .concat(line.slice(fillNumber)); // Append any remaining elements
    });
}

Answer №2

Concise solution

To achieve the desired result of creating 'x's in specific rows and columns based on given points, the code snippet below can be utilized.

for(var j = 0; j < points.length; j++) {
    for(var k = 0; k < points[j].x; k++) {
        myMatrix[points[j].y][k] = 'x';
    }
}

Explanation

The outer loop traverses through each point in the array. The variable j serves as the counter to access the current point represented by points[j]. By extracting the row number from points[j].y, we determine the specific row where 'x's need to be placed.

An inner loop is then executed to iterate over the columns needed to be filled with 'x'. The loop runs from '0' to the value specified by point[j].x, using k as its incremental counter.

In each cell identified by the coordinates (j, k), the value 'x' is assigned, fulfilling the requirement.

Simplified approach

To enhance understanding, a clearer version of the above algorithm is presented for better comprehension.

for(var pointNumber = 0; pointNumber < points.length; pointNumber++) {
    // Selecting a point
    var currentPoint = points[pointNumber];

    // Determining the range of columns to assign 'x' within the same row
    var row = currentPoint.y;

    // Filling all designated columns with 'x'
    for(var column = 0; column < currentPoint.x; column++) {
        myMatrix[row][column] = '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

Navigating the same origin policy in Mozilla: A step-by-step guide

I have implemented YUI autocomplete in my project by creating a web service that provides suggestions. Everything works fine when both the application and the web service are deployed on the same machine. However, when I deploy the web service on a differe ...

The performance of Three.js is directly influenced by the quantity of objects present

Just completed a project in WebGL using Javascript and the 3D library known as three.js Unfortunately, the performance of the project is less than impressive - slow from the start with occasional moments of adequacy. In this game, there are: 1 car, 6 ora ...

Getting the highest level object in a nested Angular component structure

Currently, I am in the process of developing a query builder using Angular that bears resemblance to the JQuery builder. However, I have encountered an issue related to emitting the data. Whenever I click on the addGroup or addRule buttons, a new group is ...

Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected. Here's where I am making a request: https://github.com/Marred/ ...

What is the best way to achieve varying margins when adding divs in CSS?

Encountering CSS margin issues when adding new divs. Desiring a large margin between the Create Div button and minimal margin between Example Text Here. The desired outcome Margin is too small between Create Div button and Example Text Here, but good bet ...

Receive notification of alert content when it is displayed

Having an HTML page with the following script: <Script> function Run() { alert("The Content Here"); return true; } </script> <button onclick="Run();">I Want It Now</button> If I were to open this page using firefox or Chrome, and ...

"Want to learn how to dynamically disable an input field in AngularJS when another field is selected? Find out how to achieve this using the

Hey there, I'm dealing with two input fields. Input field A is a drop-down menu and input field B. They both have the same value (same ng-model). My goal is to clear the second input field whenever the user selects an option from the dropdown. Can any ...

Get the elements of the array if the in_array() function verifies their presence

I am dealing with a complex multi-dimensional array structure: Array ( [0] => Array ( [item_no] => 1.01 [sor_id] => 2 [selected_qty] => 7 [price] => 3 [type] => S ...

Validation of hidden fields in MVC architectureUsing the MVC pattern to

Depending on the selections made in the dropdown menu, certain fields will appear and disappear on the page. For example: <section> @Html.LabelFor(model => model.AuctionTypeId) <div> @Html.DropDownList("AuctionTypeI ...

React project automatically refreshing when local server generates new files

I have developed a tool for developers that allows them to retrieve device data from a database for a specific time period, generate plots using matplotlib, save the plots locally, and display them on a webpage. The frontend is built using create-react-app ...

WordPress AJAX call results in a response code of zero

TL;DR: Unique - Go straight to code below for issue. You can view the demo I am working on by following this link. In my `functions.php` file, I first localize my script: function ajaxurl(){ wp_enqueue_script( 'product-selector', get_templ ...

Learn how to effortlessly integrate and utilize a bpmn file in a Vue component by leveraging the raw-loader

As a newcomer to bpmn-js, I am facing the challenge of importing and utilizing a .bpmn file within a vue.js component (BPMNViewer.vue). Despite my efforts in researching, I could only find recommendations to use the raw-loader. Consequently, I am currently ...

A guide to displaying the date retrieved from a JSON data file API request using JavaScript

How can I display the date from a JSON data file API call using JavaScript? I am facing difficulty in showing the date on the dashboard display page. I am utilizing JavaScript with async-await for calling the API, and Bootstrap 4 for design. The function ...

Rejuvenating your HTML content with AJAX over time

My HTML page contains links to charts that refresh every time the page is reloaded. A friend mentioned that AJAX can automatically refresh the chart at specified intervals without reloading the entire HTML page. I would appreciate any help with the HTML ...

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

The conditional rendering issue in Mui DataGrid's renderCell function is causing problems

My Mui DataGrid setup is simple, but I'm encountering an issue with the renderCell function not rendering elements conditionally. https://i.sstatic.net/MEBZx.png The default behavior should display an EditIcon button (the pencil). When clicked, it t ...

Update the controller variable value when there is a change in the isolate scope directive

When using two-way binding, represented by =, in a directive, it allows passing a controller's value into the directive. But how can one pass a change made in the isolated directive back to the controller? For instance, let's say there is a form ...

What is the process for building a JSON-formatted dictionary?

My intention is to structure my data in a way that can be accessed using a specific key. The current arrangement looks like this: const dict = []; dict.push({"student": "Brian", "id":"01", "grade":& ...

Deleting a character creates an error

I am conducting a small experiment with a simple goal: to filter and search for users whose names match the current value typed into an input text field. To implement this functionality, I am using RegExp(). Everything works well except when I delete a cha ...