What is the best way to evaluate individual branches of a decision tree?

I'm looking to streamline the comparison of single paths within a decision tree using a JavaScript function.

Currently, I can only compare nodes by adding them up, which limits my ability to analyze individual paths. Instead, I want to focus on one path at a time and then move on to the next one for comparison.

For instance, let's consider the following scenario: the next decision should fall within a range of -3, with the numbers provided as [9, 8, 6, 5, 3, 2, 0]. The sum of the list represents the value, and the target is to find the path with a length of 6 containing the highest value.

                      2 - 0
                  3 <
               5<     0 
             /    2 - 0
           6 
          /  \    2 - 0
               3<
                  0
     8         2 - 0
       \    3<
   /    5 <    0
            2 - 0

9               2 - 0
            3 <
         5<     0 
   \   /    2 - 0
     6 
       \   2 - 0
        3<
           0

The paths to be compared are:

[9,6,3,0],
[9,6,3,2,0],
[9,6,5,2,0],
[9,6,5,3,0],
[9,6,5,3,2,0],
[9,8,6,3,0],
[9,8,6,3,2,0],
[9,8,6,5,2,0],
[9,8,6,5,3,0],
[9,8,6,5,3,2,0],

Is there a way to efficiently compare only two paths at a time instead of evaluating all paths simultaneously?

Edit 1 :

Here is the code I have so far:

const numbers = [9, 8, 6, 5, 3, 2, 0];
const starting_node = Math.max(...numbers) + 3;

const path = (current_node, memo ={}) => {
  if (current_node in memo) return memo[current_node];
  if (current_node == 0) return [[]];
  let paths = [];
  let tmp_nodes = [];
  for (n of numbers) {
    if (n >= current_node - 3 && n < current_node) {
      tmp_nodes.push(n);
    }
  }
  for (let tmp of tmp_nodes) {
    const tmp_path = path(tmp);
    const tmp_paths = tmp_path.map(way => [tmp, ...way]);
    paths.push(...tmp_paths);
  }
  memo[current_node] = paths; 
  paths = paths.filter(x => x.length <= 6);
  return paths;
};

const bestPath = all_paths => {
  all_paths = all_paths.filter(x => (x.length = 6));
  let bestValue = 0;
  let bestPath = null;
  for (let path of all_paths) {
    let value = 0;
    for (node of path) value += node;
    if (value > bestValue) {
      bestValue = value;
      bestPath = path;
    }
  }
  return bestPath;
};
const path_array = path(starting_node);
console.log(bestPath(path_array));

This code works well, but it runs into a stack overflow error when dealing with a large amount of data (e.g., over a thousand numbers). In reality, the range is -360 instead of -3.

Main Issue: Too much data causing performance issues

Potential Solution: Implement a method to compare only two paths at once during the calculation process

Question: What approaches can be used to compute only two paths for comparison at a time?

Answer №1

After implementing a merge sort algorithm and including performance time calculations for both your solution and the merge sort solution, it is evident that the merge sort outperforms the other method in this particular scenario. The merge sort compares two arrays at a time, making it more efficient until it reaches the desired outcome. I recommend trying this on larger datasets to see if the improved performance holds.

const numbers = [9, 8, 6, 5, 3, 2, 0];
const starting_node = Math.max(...numbers) + 3;

const path = (current_node, memo ={}) => {
  if (current_node in memo) return memo[current_node];
  if (current_node == 0) return [[]];
  let paths = [];
  let tmp_nodes = [];
  for (n of numbers) {
    if (n >= current_node - 3 && n < current_node) {
      tmp_nodes.push(n);
    }
  }
  for (let tmp of tmp_nodes) {
    const tmp_path = path(tmp);
    const tmp_paths = tmp_path.map(way => [tmp, ...way]);
    paths.push(...tmp_paths);
  }
  memo[current_node] = paths; 
  paths = paths.filter(x => x.length <= 6);
  return paths;
};

const bestPath = all_paths => {
  all_paths = all_paths.filter(x => (x.length = 6));
  let bestValue = 0;
  let bestPath = null;
  for (let path of all_paths) {
    let value = 0;
    for (node of path) value += node;
    if (value > bestValue) {
      bestValue = value;
      bestPath = path;
    }
  }
  return bestPath;
};
//-----merge sort algorithm---------
const sumArr = arr => arr.reduce((acc, next)=> acc+next)
function merge(arr1, arr2){
    if (sumArr(arr1) > sumArr(arr2)) {
        return arr1
    } else if(sumArr(arr1) < sumArr(arr2)) {
        return arr2
    } else {return arr1}
}
function mergeSort(arr){
    if(arr.length <= 1) return arr[0];
    let mid = Math.floor(arr.length/2);
    let left = mergeSort(arr.slice(0,mid));
    let right = mergeSort(arr.slice(mid));
    return merge(left, right);
}
//-----end of merge sort algorithm------

const path_array = path(starting_node);
const start = performance.now()
console.log(bestPath(path_array));
const end = performance.now()
console.log("bestPath performance ", end-start)
const start2 = performance.now()
console.log(mergeSort(path_array))
const end2 = performance.now()
console.log("mergeSort performance ", end2-start2)

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 Angular to create HTTP routes in conjunction with Node.js

My current challenge involves trying to access a .json file that contains my portfolio. I have set up my backend using express js, and am attempting to retrieve the data using angular in the following manner: $http.get("data/items.json") .success(function ...

Adjust the z-index of the div to control the overflow scrollbar

I am facing an issue with a div that has a horizontal scrollbar and an image (or another div) positioned over the entire page using absolute positioning. The problem is I wish to scroll the div that is beside the image. For anchor links (a), I have set the ...

Tips for maintaining wallet connectivity through page refresh with UseEffect

I am working on a function that utilizes the UseEffect to maintain wallet connectivity even when the page is refreshed. Here is the code snippet for my NavBar component: const NavBar = ({ accounts, setAccounts }) => { const isConnected = Boolean(acc ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

The sequence of data and the final event triggered by http.createServer

const server = http.createServer(async (request, response) => { if (request.method === "POST") { var data = ""; request .on("data", async (chunk) => { console.log("1"); data + ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

The MongoDB Node cursor could not be located due to a false timeout setting

In my nodejs/express server, I am attempting to merge and sort sorted results from multiple mongodb collections to create a sorted CSV file. My method involves keeping the mongodb cursors alive (without timing out) until all data is read or an error occurs ...

Showing button based on a particular value

I am trying to dynamically display a button based on the value of the sendSMS property for the logged-in user. I have added this property in the viewer model, which is connected to the user's base model. However, I am encountering difficulties with us ...

Extract data from an HTML page using the .NET framework

I am trying to extract data from an HTML page using C# code. I am currently loading the page as a string with System.Net.WebClient and utilizing HTML Agility Pack to retrieve information within HTML tags such as forms, labels, and inputs. The issue arises ...

Whenever I try to utilize the "ng-list" in JavaScript, I encounter issues accessing the variable model

HTML <input type="text" ng-list ng-model="OtherHobby" />{{OtherHobby}} <br /> {{AllHobbys}} Javascript $scope.OtherHobby = []; $scope.AllHobbys = $scope.OtherHobby; I ran a test on this piece of code. The variable "OtherHobby" w ...

concern about Cross-Origin Resource Sharing

I currently have a Node.js backend with the following CORS configuration: app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "Orig ...

Having trouble getting CSS animations to work in Safari when triggered by JavaScript

By utilizing a basic CSS animation, I've managed to create a fade-in effect that relies on opacity. To kickstart the animation, I use JavaScript to ensure it waits until the browser finishes loading. While this method works seamlessly on Firefox and C ...

What is the best way to update the displayed data when using Mobx with an observable array?

Is there a way to re-render observable array data in Mobx? I have used the observer decorator in this class. interface IQuiz { quizProg: TypeQuizProg; qidx: number; state: IStateCtx; actions: IActionsCtx; } @observer class Comp extends Rea ...

Initializing arrays at the class scope in C++11

Having experience with Java and Ruby, I find coding simple tasks in C++ to be more challenging... I am looking to initialize an array in the constructor of a class with predetermined values that can be accessible to all methods within the class. It's ...

Tips for correctly linking an Event Listener to the worldwide 'window' in Angular 6 and higher

Situation Within our Angular 6 application, an iframe is embedded to showcase third-party data. To facilitate secure cross-domain communication, the child iframe sends messages to the parent Angular app using window.postMessage() API. To receive these mes ...

Retrieve data from a JSON file to assign to a variable, then access another API to retrieve a second

I am completely new to the world of javascript and json. My previous experience with javascript was quite minimal, about 12 years ago. So, please bear with me as I try to explain my current issue. The problem I am facing involves retrieving a second API UR ...

Develop a slider feature based on radio button selection

I am currently working with radio buttons for ticket selection. <div> <input type="radio" name="ticket" value="Standard"> Standard <input type="radio" name="ticket" value="Express"> Express <input type="radio" name="ticket" value= ...

Adjust the color of an item when scrolling

I am trying to create an object that changes color after scrolling 100px down and reverts back to its default color when scrolling back up. I have tried using this code, but it is not working properly: Here is the jQuery code snippet: $(window).scroll(fu ...