JavaScript algorithm for determining the most optimal combination (with the fewest items) of lengths that are under a specified threshold

What is the optimal way to select a combination of n values so that their sum (n1+n2+n3+n4+n5) is minimized?

maxDiff = D
requiredLength = L

lengthArray = [l1, l2, l3, l4, l5, l6]

1st constraint,
diff = L - (n1*l1 + n2*l2 + n3*l3 + n4*l4 + n5*l5)

2nd constraint,
0 >= diff <= D

In this scenario, the l values represent various sheet lengths (e.g. 1000mm, 1100mm, ..., 2000mm, etc.) The user inputs the maximum required length, represented by L. The goal is to determine the best combination of n values (greater than or equal to 0) that will minimize the number of sheets needed.

If there is a difference, it signifies the gap between the sheets and could potentially be zero.

Answer №1

If you're looking for a solution using dynamic programming, here's how to approach it:

Start by creating an array A of length L+1 with item counters set to 0 and the last added item.

Iterate through the array from index range k, going from A[i] to A[l].

If adding item li to A[k-li] results in a better count in the cell A[k] (lower value), update the current value in A[k]. Here's the pseudocode:

if (A[k-l[i]].count + 1 < A[k].count) 
   {
     A[k].count = A[k-l[i]].count + 1; 
     A[k].item =  l[i];
   }

Finally, check if the item set in A[L] can be found. If not, backtrack to find the nearest result.

To retrieve the items, move down by A[k].item steps.

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

Exploring Chrome's WebUSB Functionality with AngularJS

Recently, I encountered a challenge while utilizing WebUSB APIs for Chrome through AngularJS. This particular project involves accessing an esc/pos thermal printer for the purpose of printing invoices. In typical JavaScript: HTML: <button id="connect ...

Processing file to retrieve information (JavaScript)

As someone who is new to the world of JavaScript and website development, please forgive me if this question seems a bit basic. The concept is to have a popup message appear on every page with some information. The issue arises when wanting to change this ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Calculate the date difference in Nuxt by leveraging the @nuxtjs/moment module

I'm a Nuxt newbie facing an issue with calculating the difference between two dates (user input date and current date). The code I am using works fine in most cases, but when the input date is '2020-03-31' or '2020-01-30', the cons ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

What is the best way to execute synchronous calls in React.js?

Currently, I am a novice in working with React JS and I have been tasked with implementing a feature to reset table data in one of our UI projects. Here is the current functionality: There is a save button that saves all overrides (changes made to the or ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

Troubleshooting my code: The mystery of why Google Map directions won't cooperate!

Can anyone help me figure out why my code for drawing a path between multiple points on a map isn't working? I've tried the code below, but it doesn't draw any paths. What could be causing this issue and how can I solve it? var myTrip = [] ...

Unable to utilize JavaScript objects extracted from JSON

Working on developing a web application using AngularJS has led me to encounter an issue. I have a PHP server that retrieves data from an SQL database and encodes it into JSON. Utilizing the Angular $http service on the client side, I am able to successful ...

Is there a way to ensure that a certain block of code in Typescript is executed only after an API call has been completed?

When making an API call, I need the code after the call to wait until the API call finishes. In my function called this.api_call, it calls the API and only returns an array returnValue once the call is complete. let returnValue = this.api_call(data); // ...

Store the output of a mysql query in a variable for future reference

As I work on developing a backend API for a private message system, I have encountered a challenge with one of my functions. The issue arises when I attempt to store the result of an asynchronous call in a variable for future use. Here is the code snippet ...

Troubleshooting: The issue of Vue (v-on) not recognizing my function

I am brand new to Vue and JS, so please bear with me as I ask some "silly" questions. Within my Vue-Pet-Project, I have implemented a self-authored class module called Sudoku. In this module, I aim to find solutions using backtracking. Upon clicking the " ...

Achieving a continuous 2-layer css parallax background in Firefox using css properties "transform" and "perspective" while ensuring the background remains visible beyond content height

You are my final hope. I made a decision to add an update to the Page of my brother's store. One of the new features I wanted was a simple parallax background with two layers to create a sense of depth while scrolling. At first, I managed to make it ...

Ways to display divs by moving the mouse across the entire screen, rather than just over the specific element

I successfully implemented functionality to hide and show my classes when the user hovers over a specific element. However, what I really want is for these classes to show up when the user moves their mouse anywhere on the screen, not limited to just the s ...

Incorporating nested maps in JSX for efficient data manipulation

{normalizedData.map(item => <div key={item.display_date_numberic}> <div>{item.display_date_numberic}</div> </div> {!isEmpty(item.applicants) && item.applicants.map(applicant => <div className= ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

The secret equation for unravelling an array of gridded numbers, including

I have been using this method to flatten a multidimensional array (x,y,z): array = new byte[GridSizeX*GridSizeY*GridSizeZ]; index = x + y * GridSizeX+ z * GridSizeX* GridSizeY; I am now trying to figure out how to adjust this formula to handle n ...

What is the most efficient way to identify the top n instances of a specific value within an array using Typescript or JavaScript?

Working with TypeScript, I am dealing with an array of objects that may contain the same values as other objects within the array. For example, the following array consists of objects with the value "intent". My goal is to identify the top 3 most commonly ...