Discover every conceivable combination of items that results in the total values adding up to a specific number

Wanting to achieve this using TypeScript.

I am dealing with an array of objects, each containing a property named rating. Here is how the array looks:

const objects = [{"name":"foo","rating":4}, {"name":"bar","rating":5}, {"name":"foobar","rating":2}]

Given a target rating, let's call it destinationRating, for example: const destinationRating = 11. I aim to extract from these objects an array containing around 20 strings structured as key1;key2;key3, where key1 and so forth are keys from the objects array. The goal is for the sum of all selected objects to meet or exceed the destinationRating, with a minimum requirement of 3 selected objects. I am unsure of the best approach to developing such an algorithm.

The desired output would resemble this: [0:"0;1;2"], assuming that the first 3 objects in the objects array satisfy the criteria.

Answer №1

Within this proposal lies a method that exhaustively generates combinations of indices based on the specified conditions, ensuring an accurate result is obtained.

The outcome comprises strings containing the indexes from the provided array that satisfy the specified sum condition.

function findCombination(array, property, sum) {
    function check(part, i) {
        var results = [], current, total;
        while (i < sizeOfArray) {
            current = part.slice(0);
            current.push(i++);
            document.write(current + '<br>');
            total = current.reduce(function (result, item) { return result + array[item][property]; }, 0);
            if (total < sum) {
                results = results.concat(check(current, i));
            }
            if (current.length >= 3 && total === sum) {
                results.push(current.join(';'));
                break;
            }
        }
        return results;
    }

    var sizeOfArray = array.length;
    return check([], 0);
}

var dataObjects = [{ "name": "id0", "rating": 4 }, { "name": "id1", "rating": 5 }, { "name": "id2", "rating": 2 }, { "name": "id3", "rating": 6 }, { "name": "id4", "rating": 8 }, { "name": "id5", "rating": 3 }, { "name": "id6", "rating": 1 }];

document.write('<pre>' + JSON.stringify(findCombination(dataObjects, 'rating', 11), 0, 4) + '</pre>');

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

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...

Chatting with a Discord bot

I am currently working on a Discord bot that will execute specific functions based on the questions asked, most of which are yes or no queries. Upon responding with "yes," a particular function should be performed, while answering "no" would terminate t ...

Adding pictures to Cloudinary

My goal is to upload files directly to Cloudinary using nodejs. I have managed to achieve success when I manually set the path of the image I am uploading, as shown below: cloudinary.uploader.upload('./public/css/img/' + data.image) However, whe ...

Tips for pulling out particular information from a string?

There is a text document that needs to be parsed. The objective is to extract the strings between "@5c00\n" and "@ffd2\n", as well as between "@ffd2\n" and "@". @5c00 81 00 00 5C B1 13 3E 01 0C 43 B1 13 A6 00 1C 43 B1 13 38 01 32 D0 10 00 ...

What is the process for obscuring items using the depth buffer in three.js?

In my current project using three.js, I am working on a 2D game where I need to render background scenery followed by a transparent quad that still writes values to the depth buffer even though it has an opacity of zero. The challenge arises when trying to ...

Component fails to update when state updated using useState()

In my current project, I am facing an issue with a parent (App) and child (MUIDatatable) component setup. The child component is a datatable that requires a columns prop to define the structure of the columns, including a custom render function for one of ...

What is the best way to display a JavaScript loop on a webpage instead of just in the console?

As a beginner in programming, I have taken on the challenge of creating my own FizzBuzz program. The goal is to write a program that displays numbers from 1 to 100. However, for multiples of three, it should output "Fizz" instead of the number; for multipl ...

How can one identify a concealed glitch that exclusively occurs for a particular individual or hardware in a React environment?

Is it possible to identify a bug that occurs only with a particular individual or hardware in a React application? This bug is invisible and never appears during tests, but only manifests with a specific client within my company. Do you have any tips on h ...

Exploring the power of Javascript for number lookup

I am currently working on a coding project using TypeScript and JavaScript to locate a specific number provided by the user within a list. The goal is to display whether or not the number is present in the list when the 'search' button is pressed ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Tips for exchanging JavaScript variables with PHP using AJAX

Hey there, I'm new to JavaScript and I've hit a roadblock with passing variables to PHP using Ajax. <script> $date = "123"; $.ajax({ url: './record.php', type: "POST", ...

"The challenge of handling multiple HTTP requests in Node.js without receiving proper responses

Hello there, I've been struggling with a Node.js HTTP request issue involving a loop. The loop size is 1728, but the response seems to be missing as it gets stuck at 1727. I've been trying to solve this problem for the past three days with no luc ...

Having trouble with json_decode in PHP? Learn how to effectively retrieve JSON data in PHP

My attempt to update content using Angular on the front-end and PHP on the server side is encountering some issues. Below is the code snippet being used: In the main js file, a call for update: updateinscription: function($params) { var urlphp = "ht ...

Extending Error object disrupts `instanceof` validation in TypeScript

Could someone clarify why the error instanceof CustomError part of the code below returns false? class CustomError extends Error {} const error = new CustomError(); console.log(error instanceof Error); // true console.log(error instanceof CustomError); ...

Updating the Animation for Datepicker Closure

While using the date picker, I want it to match the width of the input text box. When closing the date picker, I prefer a smooth and single motion. However, after selecting a from and to date, the datepicker no longer closes smoothly. I have attempted sol ...

Discovering the most efficient route between two locations within a grid of values

I'm currently working on a game where I need to find the shortest route between two points. https://i.sstatic.net/jBnEd.png In my map, I have a 2D array called matrix: Node[][], class Node{ index: { x: number, y: number }, isAvai ...

What is the process for importing libraries from a different local directory?

What I mean by that title is: I have some code that was generated and now I am incorporating it into my Angular application. Currently, I am installing this code as a package using npm, but it is causing issues with my deployment setup. So, I would like ...

JavaScript variable scoping problem arises when there are conflicts between two functions that utilize callbacks

I am trying to merge two arrays, but in the current code I am only able to access the txs_history array. getFirstArray(function(txs) { getSecondArray(function(txs_history) { txs.concat(txs_history); res.send(txs_history); }); } ...

Count Scroller - Finding a Solution for _.debounce

Issue with Counter I have a counter that should increase or decrease by one each time the user scrolls up or down. The problem I'm facing is that my counter $('html').on('mousewheel', function (e) { var delta = e.originalEve ...

Using Angular directives to dynamically add event listeners with the ng-repeat directive

I am currently working with a directive that includes event listeners for an element in the link function. For example: ... link: function(scope, element) { // this gives us the native JS object var el = element[0]; el.draggable = true; ...