Instructions for rearranging the configuration of a 2D array?

A 2-dimensional array is created from a string called matrix:

131 673 234 103 018
201 096 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 037 331

After parsing, it becomes an array of arrays like this:

[
  [131, 673, 234, 103, 018],
  [201, 096, 342, 965, 150],
  [630, 803, 746, 422, 111],
  [537, 699, 497, 121, 956],
  [805, 732, 524, 037, 331]
]

But now, the array needs to be restructured to look like this:

[
  [131],
  [201,673],
  [630,096,234],
  [537,803,342,103],
  [805,699,746,965,018],
  [732,497,422,150],
  [524,121,111],
  [037,956],
  [331]
]

This new array follows the up-left diagonals of the string or current array.

The string may need to be manipulated into one line and then rebuilt with newlines in specific positions for the current code to function properly. However, the implementation of this process is not clear at the moment.

The code used to create the array is as follows:

matrix.split("\n").reduce((a, b) =>
{
    a.push(b.split(" ").map(x => parseInt(x)));
    return a;
}, []);

(matrix refers to the variable holding the string)

Ideally, only the reducer function could be replaced to achieve the desired result, but any solution would be greatly appreciated.

Answer №1

I made some adjustments to your method in order to shift each item of the inner arrays onto the corresponding diagonal. I utilized the Array::unshift() method to add new elements to the beginning of a diagonal array.

const matrix = "131 673 234 103 018\n201 096 342 965 150\n630 803 746 422 111\n537 699 497 121 956\n805 732 524 037 331";

let res = matrix.split("\n").reduce((acc, curr, idx1) =>
{
    curr.split(" ").forEach((n, idx2) =>
    {
        // Determine the index of the diagonal to which this item belongs.
        let dIdx = idx2 + idx1;

        // Add the element to the appropriate diagonal.
        acc[dIdx] = acc[dIdx] || [];
        acc[dIdx].unshift(parseInt(n));
    });

    return acc;

}, []);

console.log(res);

Answer №2

To start, you can navigate from the left side and then proceed to the bottom, moving from left to right and collecting the diagonal values from the array.

function retrieveDiagonalValues(x, y) {
    var result = [];
    while (x >= 0 && y < data[0].length) result.push(data[x--][y++]);
    return result;
}

var data = [[131, 673, 234, 103, 018], [201, 096, 342, 965, 150], [630, 803, 746, 422, 111], [537, 699, 497, 121, 956], [805, 732, 524, 037, 331]],
    result = [],
    i = 0, j = 1;
 
while (i < data.length) result.push(retrieveDiagonalValues(i++, 0));
while (j < data[0].length) result.push(retrieveDiagonalValues(data.length - 1, j++));

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

My approach is as follows:

const input = `131 673 234 103 018
201 096 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 037 331`;

let matrix = input.split('\n').map(line => {
  return line.split(' ').map(elem => parseInt(elem.trim()));
});

let rows = matrix.length,
    cols = matrix[0].length,
    numDiags = rows + cols - 1,
    diagLimit = Math.max(matrix.length, matrix[0].length);

let diagMatrix = [...Array(numDiags)].map((_, diagNum) => {
  let diag = [];
  
  for (let i = 0; i < diagLimit; i++) {
    let r = (diagLimit - 1) - i,
        c = i - (diagLimit - 1) + diagNum;
    
    if (r >= 0 && c >= 0 && r < matrix.length && c < matrix[0].length) {
      diag.push(matrix[r][c]);
    }
  }
  
  return diag;
});

console.log(diagMatrix);

This algorithm loops through each diagonal of length max(rows, cols) within the matrix, including only the elements within the overlapping region. It's designed to accommodate rectangular matrices, allowing for potential optimizations when working with square matrices exclusively.

Answer №4

Check out this handy trick you can utilize. Take a look at the organization of the indices in your matrix:

00  01  02  03

10  11  12

20  21

30

If you observe closely, the sum of indices on each diagonal equals the same number, which corresponds to the index in the resulting array.

You can leverage this insight to easily convert your matrix by implementing the following function:

const convertMatrix = (matrix, rows = matrix.length, cols = matrix[0].length) => {
    const result = [];

    for (let j = 0; j < cols; j++) {
        for (let i = 0; i < rows; i++) {
            const index = i + j; // this will be the resulting index
            if (index >= result.length) result[index] = []; // dynamically create new rows
            result[index].push(matrix[i][j]);
        }
    }

    return result;
};

console.log(JSON.stringify(convertMatrix([ [131, 673, 234, 103,  18]
                                     , [201,  96, 342, 965, 150]
                                     , [630, 803, 746, 422, 111]
                                     , [537, 699, 497, 121, 956]
                                     , [805, 732, 524,  37, 331]
                                     ])));

I hope you find this information useful.

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

Managing API calls through Next.js routing

Here is a next.js handler function for handling api requests on our server. I am looking for assistance on how to access a variable between request methods. Any help would be greatly appreciated. export default function handler(req, res) { if(req.met ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...

ExpressJS refuses to wait for my promise to be fulfilled

I'm in the process of creating a search-page on my server. Whenever the endpoint is accessed and the user waits for the search function to deliver the results and display them on the page, Express somehow redirects to the 404 handler instead. An error ...

Extracting JSON Value from a Script Tag

Seeking a more efficient method to extract the designated JSON value (highlighted in yellow) that is currently acquired using the code below. Although effective, it lacks efficiency. $("head > script:nth-child(55)").text().trim().replace(" ...

Learn how to integrate Bootstrap with Vue.js TreeView in this tutorial

If you're looking to create a treeview using Vue.js, the code structure would resemble something like this: HTML: <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div ...

The Node.js engine isn't updating to support compatibility with Firebase functions

Encountered First Failure Below is the content of package.json "engines": { "node": "8.0.0" }, Error: The engines field in the functions directory's package.json is unsupported. You can choose from: {&quo ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

Tips on embedding a textField into a designated row within a table by clicking a button with the help of reactjs and material ui

I need assistance adding multiple text fields to a specific row within a table when a designated row's "add" button is clicked. Currently, I am able to add a text field when the button is clicked, but it adds the text field to every row in the table. ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Setting up route handlers in Node.js on a pre-initialized HTTP server

Is there a way to add route handlers to an http server that is already instantiated? Most routers, including express, typically need to be passed into the http.createServer() method. For instance, with express: var server = http.createServer(app); My r ...

Is it possible to determine if jQuery find returns true or false?

Snippet of HTML Code <div class="container1"> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <div class="box3">Box 3</div> </div> <div clas ...

Adding the children of JSON objects to every individual div element

How can I add each day's players [day-1, day-2, day-3, day-3] wrapped in a <span> into the .card-body section as required? The goal is to load only four card-body. var vehicles = { "day-1": { "player-1-1": "Ford", "player-1-2": "BMW ...

A guide to integrating gatsby-remark-images-grid in markdown with Gatsby.js

Currently, I am working on creating a blog using Gatsby.js with markdown and I want to incorporate CSS grid into my blog posts to showcase a beautiful grid layout of images. I am aware that Gatsby offers incredible plugins to address various challenges. ...

Error in parsing string data in Django Chart.js ajax using javascript

I'm currently working on creating a chart web page using Django and Chart.js within the views.py file of the Django framework. class ChartView(TemplateView): template_name = 'graph.html' def get_context_data(self, **kwargs): ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

Is there a way to prevent a link from activating when I click on one of its internal elements?

Within a div nested inside an "a" tag (specifically in Link within next.js), there is another div labeled as "like." When clicking anywhere within the main div, the intention is for it to redirect to the destination specified by the "a" tag. However, if th ...

Error retrieving user by provider account ID using Google and Firebase adapter with Next Auth

Encountering an issue while trying to integrate Google Provider with Firebase Adapter in Next Auth. Upon selecting an account, the following error is displayed: Running Firebase 9 TypeError: client.collection is not a function at getUserByProvider ...

Tips for eliminating the backslash introduced by JQuery

Switching back from framework 4.5 to 4.0 caused several issues that needed fixing. One significant change I noticed was that jQuery started escaping double quotes. Is there a way to stop this behavior? I attempted datatest = datatest.replace("\\ ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...