简体   繁体   中英

Get All possible combinations of objects, where sum of values matches number

Looking to do this in typescript.

I have an array of objects, where each object has a property called rating . The array looks like so:

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

Now I have a target rating, destinationRating , this for example: var destinationRating=11 . From these objects, I need to get an array of, say 20 key1;key2;key3 shaped strings, where key1 and so on, are the keys from the objects array, where the sum of all the objects selected is at least destinationRating . 3 selected objects minimum. I have no idea on how I should apporach the creation of such an algorithm.

The end result should look like this, [0:"0;1;2"] , in the case that the first 3 objects of the objects array match the criteria.

This is a proposal which generates all combinations of the indices (as long as they are necessary, see output) and checks the given conditions and returns the wanted result.

The result set contains strings with the indices of the given array which match the wanted sum of the named property.

 function combination(array, property, sum) { function c(part, i) { var result = [], p, s; while (i < n) { p = part.slice(0); p.push(i++); document.write(p + '<br>'); s = p.reduce(function (r, a) { return r + array[a][property]; }, 0); if (s < sum) { result = result.concat(c(p, i)); } if (p.length >= 3 && s === sum) { result.push(p.join(';')); break; } } return result; } var n = array.length; return c([], 0); } var objects = [{ "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(combination(objects, 'rating', 11), 0, 4) + '</pre>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM