effectively determine which elements of an array have been added together

My input consists of two arrays. The first array is called dels and looks like this:

const dels = [ // up to 50 possible
  {no: 491, weight: 1348},
  {no: 492, weight: 694},
  {no: 1054, weight: 4104},
  {no: 1181, weight: 2636},  // *
  {no: 2096, weight: 4084},
  {no: 2201, weight: 4064},
  {no: 2296, weight: 2364},
  {no: 2365, weight: 1670},
  {no: 2632, weight: 4084},
  {no: 2891, weight: 2424},
  {no: 3051, weight: 2414},  // *
];

The second array, sums, holds some values as well:

const sums = [5050, 24836]; // up to 4 possible

While the structure remains fixed, the actual numbers are sourced externally.

I've established that every number in the sums array represents the sum of specific weights from the dels array (each dels item used only once).

Hence, these assumptions hold true:

const sumDels = dels.reduce((a,i) => a + i.weight, 0);
const sumSums = sums.reduce((a,i) => a + i, 0);
sumDels === sumSums // is true

sumDels.every(x => x.weight > 0) // is true

I seek an algorithm that efficiently provides me with potential combinations leading to the given sums.

An example outcome might resemble this:

const goodResult = [ // <-- array of possible combinations (theretically, there could be more than one)
  [                  // <-- `dels` array mapped with `sumIdx`
    {no: 491, sumIdx: 1},
    {no: 492, sumIdx: 1},
    {no: 1054, sumIdx: 1},
    {no: 1181, sumIdx: 0},  // *
    {no: 2096, sumIdx: 1},
    {no: 2201, sumIdx: 1},
    {no: 2296, sumIdx: 1},
    {no: 2365, sumIdx: 1},
    {no: 2632, sumIdx: 1},
    {no: 2891, sumIdx: 1},
    {no: 3051, sumIdx: 0},  // *
  ]
];

An inefficient solution would involve trying out all permutations, but with sums.length==4 and dels.length==50, we're looking at a whopping 1267650600228229401496703205376 possible combinations! Quite overwhelming...

Answer №1

In the discussion, it was brought up that this issue is commonly referred to as the subset sum problem. From what I've gathered, the typical approach involves exhaustively testing all possible combinations while stopping early if a combination is determined to be invalid.

Following this train of thought, I stumbled upon another insightful response on Stackoverflow, which offers an elegant recursive solution.

Although it only deals with one sum at a time (while my array could potentially contain up to 4 numbers), it serves as a valuable starting point for implementing a complete solution.

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

Incorporating CCPoint into CCArray

In my quest to select a random CCPoint from the CCArray, and subsequently exclude that point to avoid duplication, I encountered an issue with the following code snippet: myArray->addObject(pos1); In this scenario, pos1 denotes a CCPoint, while my ...

executing functions that return a JSX component within the render method

In an effort to enhance readability, I am striving to condense the length of the render() method by utilizing class methods that contain isolated JSX elements. A snag arises when attempting to apply this technique to more than one JSX element. Despite en ...

Count the occurrences of each symbol in the Java matrix

How can we determine the frequency of each letter in a randomly filled 10x10 two-dimensional array containing both uppercase and lowercase English letters? ...

Solution for adjusting line width on Windows in Three.js

I'm currently working on creating a dynamic 3D coordinate system using the Three.js library. My goal is to add some thickness to the axes, which I've been able to achieve by adjusting the LineBasicMaterial's linewidth parameter. The code sn ...

Vue.js: API request taking too long during mounted lifecycle

I am facing an issue with API data in my Vue js project. The page loads quickly but the data from the API takes more than 5 seconds to load. Strangely, the API response appears very fast in the console. I have implemented the API in a separate file called ...

Is there a way to utilize namespace import without bringing in all the other imports as well

Within our angular application built with typescript, we make use of lodash. Our current approach to importing lodash is demonstrated below: import * as _ from 'lodash'; //.. code which utilizes _.pluck() However, in order to optimize for tree ...

What is the process to temporarily disable a button for a brief two-second period after it has been clicked, and then

Is there a way to temporarily disable a button for two seconds after it's clicked, and then re-enable it automatically? I'm looking to achieve this functionality using OnClientClick in JavaScript - specifically, I'd like the button to run t ...

Using JavaScript to Align HTML Data to the Right or Left

I have successfully created an HTML table from JSON data and formatted it using JavaScript as required. However, I am facing a challenge with right-aligning all the amounts coming from my JSON data. I want all the numbers to be aligned to the right but I& ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

Working with deeply nested objects in JavaScript

Given the following array structure: objNeeded = [ {onelevel: 'first'}, { onelevel: 'second', sublevels: [ {onelevel: 'domain'}, {onelevel: 'subdomain'} ] }, { ...

Manipulate array elements using push and pull operations in a NodeJS API request

In my application, I utilize Mongoose to establish schemas. I have a Schema for users and a Schema for tickets (Tickit). Each time a user creates a ticket, I aim to include the ticket's id in the 'tickets' array of the user schema as shown b ...

Unable to include an additional parameter within a JavaScript function

I'm having trouble adding a parameter to the Openpopup() function - every time I try, I get an error. Can someone help me out with this? Thanks in advance. return "<a onclick='return Openpopup()' class='btn btn-info btn-lg clickBtn& ...

Can ES6 imports be directly added onto an object in JavaScript?

Let's examine the example below: import ThingA from './ThingA'; import ThingB from './ThingB'; // ... import more things const things = { ThingA, ThingB, // ... add more things to object }; While this code functions correc ...

Guide to showing specific images alongside text through Ajax and Jquery

Currently, I am faced with the challenge of displaying specific text files using jQuery and Ajax. My goal is to have a text file appear based on the image being displayed. For instance, if an image of an apple is being shown, I would like the text below i ...

A different method to generate a random number between 0 and 9 in Angular 8

Looking for an alternative to Math.floor(Math.random()*10) in Angular 8? I need to remove math.random() due to security concerns. A suggestion was made to use PRNG, but I'm not familiar with how to do that. Any assistance would be greatly appreciated! ...

Efficient method to identify distinct keys within a collection of objects using Typescript

https://i.sstatic.net/qHkff.png I am currently developing an angular application that includes: a group of filters and data records displayed in a table The columns in the table correspond to the filters, where each filter contains unique values from it ...

Passing information between VueJs3 components

I have been coding a VueJs3 Project that includes a login system, and it's working perfectly. Now, I want to display the user's logged-in account on the homepage within a div. The message should be: "You are logged in as:" followed by the userna ...

Tokenizer method utilizing strings

Imagine a scenario where strings adhere to this specific format: id-string1-string2-string3.extension In this case, id, string1, string2, and string3 can all vary in length, with extension being a standard image extension type. To illustrate, here are a ...

Using Dat GUI alongside Three.js to generate 3D text geometry based on user input, with real-time updates

Trying to utilize the combination of Dat GUI and Three.js to allow for user inputted text to generate 3D text geometry that updates in real time. Successfully achieved control over the x, y, and z positions, as well as displaying the text input box. Strug ...

Merge two arrays into a single array

I am working with an array that has the following structure: array ( [name] => name [description] => description here [first] => Array ( [0] => weight [1] => height ) [second] => Ar ...