Discovering every potential route in a 2D grid of digits from the beginning to the end, ensuring each move exceeds the previous step's value

I have a code that currently only finds 2 possible paths. How can I modify it to find all possible paths?

For example, starting with the first array [1, 32], pick a number like 32.

Next, look at the following array: [11, 21, 24, 27, 35, 37, 65]. A valid step would be any number greater than your current step from this array. So, 35, 37, and 65 are all valid steps.

Continue building the path by stepping onto the subsequent arrays in order (from top to bottom) until you reach the last one.

'use strict';

const matrix = [
  [1, 32],
  [11, 21, 24, 27, 35, 37, 65],
  [17, 22, 25, 51, 57, 63],
  [18, 56]
];

function findPaths(arrays) {
  const paths = [];
  for (let i = 0; i < arrays[0].length; i++) {
    const path = [arrays[0][i]];
    for (let j = 1; j < arrays.length; j++) {
      for (let y = 0; y < arrays[j].length; y++) {
        if (path[Math.max(0, path.length - 1)] < arrays[j][y]) {
          path.push(arrays[j][y]);
          break;
        }
      }
    }
    paths.push(path);
  }
  return paths;
}

const result = findPaths(matrix);

console.log(result); // [ [ 1, 11, 17, 18 ], [ 32, 35, 51, 56 ] ]

Answer №1

I successfully completed the task. While my solution may not be the most efficient, I am actively working on optimizing it.

const data = [
  [1, 32],
  [11, 21, 24, 27, 35, 37, 65],
  [17, 22, 25, 51, 57, 63],
  [18, 56]
];

function findPaths(arrays) {
  const paths = [];
  const maxPaths = arrays.reduce((total, arr) => total *= arr.length || total, 1);
  for (let x = 0; x < maxPaths; x++) {
    for (let i = 0; i < arrays[0].length; i++) {
      const path = [arrays[0][i]];
      for (let j = 1; j < arrays.length; j++) {
        for (let y = 0; y < arrays[j].length; y++) {
          if (path[Math.max(0, path.length - 1)] < arrays[j][y]) {
            if (!paths.some(p => p.toString() == [...path, arrays[j][y]].toString())) {
              path.push(arrays[j][y]);
              break;
            }
          }
        }
      }
      paths.push(path);
    }
  }
  return paths.filter(path => path.length == arrays.length).sort();
}

const result = findPaths(data);

console.log(result);

/*
[
  [ 1, 11, 17, 18 ],  [ 1, 11, 17, 56 ],
  [ 1, 11, 22, 56 ],  [ 1, 11, 25, 56 ],
  [ 1, 11, 51, 56 ],  [ 1, 21, 22, 56 ],
  [ 1, 21, 25, 56 ],  [ 1, 21, 51, 56 ],
  [ 1, 24, 25, 56 ],  [ 1, 24, 51, 56 ],
  [ 1, 27, 51, 56 ],  [ 1, 35, 51, 56 ],
  [ 1, 37, 51, 56 ],  [ 32, 35, 51, 56 ],
  [ 32, 37, 51, 56 ]
]
*/

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

Using Regex with JavaScript while ignoring letter case

I am trying to extract a query string from my URL using JavaScript, and I need to perform a case-insensitive comparison for the query string name. In order to achieve this, here is the code snippet that I am currently using: var results = new RegExp(&apos ...

Searching for the dimensions of an SVG file using code - is that possible?

I have a collection of unique svg files, each containing various components. Some of these components may include "port" elements that I need to exclude when determining the overall size of the svg file. Below are examples of two different svg files with t ...

Using Javascript in n8n to merge two JSON arrays into a single data structure

When working on a project, I extract JSON objects from the Zammad-API. One of the tickets retrieved is as follows: [ { "id": 53, "group_id": 2, "priority_id": 2, "state_id": 2, "organizati ...

Steps to trigger a Bootstrap modal when the user clicks anywhere on the webpage

I need assistance with setting up a Bootstrap dialogue modal to open at the clicked position on a mousedown event when a user interacts with the page. Despite my attempts, the dialogue modal is not opening where it should be. Here's what I've tri ...

Choosing a Value from a WP_Post Object in PHP

I stumbled upon this sample array/object structure: //$monday array values Array ( [menu_item1] => [menu_item2] => Array ( [0] => WP_Post Object ( [ID] => 530 [post_content] => Food selection 2 [post_title] => Food 2 ) ) Being a novi ...

The ng-repeats functionality is triggered multiple times whenever I attempt to make this call

I have a situation where I am using ng-repeat in my Laravel view to call a function from the controller. This function retrieves data from the database, performs some calculations, and then returns an array. However, I am facing an issue where the data is ...

Double Marker Challenge in Brochure

I am currently using Leaflet in conjunction with VueJs. I have encountered an issue where a double marker is appearing at a specific location when I add a marker: The code responsible for this behavior is as follows: mounted() { this.map = L.ma ...

What is the process for customizing the color of a w3.css button?

<link type="text/css" href=" https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"> <div class="w3-bar w3-red"> <a class="w3-bar-item w3-button w3-hover-blue">Button</a> </div> I am looking to implement a funct ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

Checking date entries

After customizing the date format in the Django modelform widget and jQuery datepicker, I encountered an error indicating that the field is not valid. class Sale_Invoice_Main_Page(forms.ModelForm): class Meta: model = SaleInvoice field ...

A tutorial on creating dynamic text animations: sliding text effects on web pages

Does anyone know how to create a sliding in and out effect like the one on this page: ...

Encountered an issue while trying to implement CORS using yarn

Currently experiencing the following issue: Error message: An unexpected error occurred "/home/vagrant/.cache/yarn/v1/npm-cors-2.8.4-2bd381f2eb201020105cd50ea59da63090694686/.yarn-metadata.json: Unexpected end of JSON input". Some important points to c ...

Ext 4.1 - Accessing a class instance using Ext.define()

In my code, I have a class with a method defined like this: Ext.define('MY.class.Manager', { .... .... .... manageStuff: function(){ } } Initially, the manageStuff function was only needed in one place and everything worke ...

Laravel: JavaScript Integration Problem (Current Status Concern)

I encountered an issue with the update status feature. The status is being stored correctly in the database, but the corresponding status icon does not change as expected. Upon refreshing the page, the status icon reverts to its previous position, even tho ...

Node/Express: Detecting PDF Data Size of 0

Currently, I am facing a challenge with retrieving a PDF file from my Google Cloud Storage. The URL for the PDF is stored in MongoDB entry which is causing issues when sending it to the client. It seems like the data being read is empty due to some async o ...

Positioning buttons in a grid using CSS - Tips and tricks

Help needed! Seeking professional advice. I have a few issues that I can't seem to solve on my own. Firstly, regarding the second menu - should I use padding to position it correctly? Secondly, although I managed to make the navigation bar visually s ...

how to load CSS and JS files on certain views in Laravel 5.2

Currently, I am facing a situation where I need to ensure that the CSS and JS files are loaded only on specific views in Laravel 5.2. Due to my boss's decision to eliminate RequireJS for loading JS files on our blade templates, we are now exploring a ...

Fill the table with information from a JSON file by selecting options from drop-down menus

I am currently working on a web application project that involves bus timetables. My goal is to display the timetable data in a table using dropdown menus populated with JSON information. While I believe I have tackled the JSON aspect correctly, I am facin ...

Typescript array iteration using dual parameters

I seem to be struggling with the logic behind this seemingly straightforward iteration question. My task involves iterating through an array of data based on id and code, removing data only when the code is not associated with the given id's. Let&ap ...

Using Express.js to Query a PostgreSQL Database via URL Parameters

Trying to retrieve specific information from my database via URL query is proving tricky. Currently, the response just displays all individuals in the database. exports.getPersonByName = async (req, res) => { const query = req.query.q try{ const per ...