kingmaster kingmaster - 5 months ago 13
Node.js Question

Sum multi keys depends on total number

Sum multi keys depend on total number.



i.e:
i have an object of big list or dataset of json file.

var obj = [
{ 'itemz': 'tomato', 'value': 5 },
{ 'itemz': 'potatos', 'value': 3 },
{ 'itemz': 'banana', 'value': 7 },
{ 'itemz': 'orange', 'value': 6 },
{ 'itemz': 'apple', 'value': 4 },
{ 'itemz': 'cherries', 'value': 5 },
{ 'itemz': 'watermelon', 'value': 9 },
{ 'itemz': 'orange', 'value': 8 }
];
var total = prompt("Put the number:"); // i choose 9


i want to get all result itemz that sum of 9:
in our example the result will be:

items is:

watermelon //sum=9
orange, potatos //6+3=9
apple, tomato //4+5=9
apple, cherries //4+5=9



  • itemz properties is Unique, so there is no duplicate.

  • values is not Unique.

  • i choose small numbers to count fast and to get my point.

  • if can make radio to choose for search by one itemz or two, or three maximium.

  • result must be not duplicate i.e: "potatos, potatos, potatos".

  • supports utf-8.


Answer

Something Like this:

function subsetSum(numbers, target, partial) {
  var s, n, remaining;
 partial = partial || [];
 s=0;
 for(var j=0;j<partial.length;j++){
    s=parseInt(partial[j].value)+ s;
  }

  // check if the partial sum is equals to target

  if (s === target) {
   console.log("combination is");
   var result="";
    partial.forEach(function(i){result=result+i.itemz+",";})
    console.log(result);
  }


  if (s >= target) {
    return;  // if we reach the number why bother to continue
  }

  for (var i = 0; i < numbers.length; i++) {
    n = numbers[i];
    remaining = numbers.slice(i + 1);
    subsetSum(remaining, target, partial.concat([n]));
  }
}
var obj = [
  { 'itemz': 'tomato', 'value': 5 },
  { 'itemz': 'potatos', 'value': 3 },
  { 'itemz': 'banana', 'value': 7 },
  { 'itemz': 'orange', 'value': 6 },
  { 'itemz': 'apple', 'value': 4 },
  { 'itemz': 'cherries', 'value': 5 },
  { 'itemz': 'watermelon', 'value': 9 }
];
subsetSum(obj,24);
Comments