-3

I have an array with items like:

[[ 'NAME 1',30 ]
[ 'NAME 2',120 ],
[ 'NAME 3', 90 ],
[ 'NAME 4',30 ]]

For example, I need to take sum from this array as 60, so in array it is the first and the last element.

How can I do it in node.js?

Summary: I have an array, from array I need to take x as sum value ( x is number like 90, 100). If the target number already exists in the array, that number is the result. If it does not exist, the combination of numbers should be returned, with the numbers in the combination should be as few as possible.

shaochuancs
  • 15,342
  • 3
  • 54
  • 62
Jensej
  • 1,255
  • 6
  • 21
  • 33
  • Please check https://stackoverflow.com/questions/4632322/finding-all-possible-combinations-of-numbers-to-reach-a-given-sum there is a JavaScript version on this "SubsetSum" problem. – shaochuancs Jul 03 '17 at 14:24

1 Answers1

1

Thanks to @rbarilani's code on SubsetSum problem in Finding all possible combinations of numbers to reach a given sum, here is the adjusted program which:

  1. Extract number from original 2-D array.
  2. Return number in the original array, if there is an exact match.
  3. If there is no exact match, in the possible combination, provide the least items one.

var originArr = [[ 'NAME 1',30 ], [ 'NAME 2',120 ], [ 'NAME 3', 90 ], [ 'NAME 4',30 ]];

var arr = [];
for (var i in originArr) {
  arr.push(originArr[i][1]);
}

var candidate;

subsetSum(arr, 60);

console.log(candidate ? candidate : 'No combination found');

function subsetSum(numbers, target, partial) {
  var s, n, remaining;

  partial = partial || [];

  // sum partial
  s = partial.reduce(function (a, b) {
    return a + b;
  }, 0);

  // check if the partial sum is equals to target
  if (s === target) {
    if (!candidate || candidate.length > partial.length) {
      candidate = partial;
    }
  }

  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]));
  }
}
shaochuancs
  • 15,342
  • 3
  • 54
  • 62
  • 3.If there is no exact match, in the possible combination, provide the least items one. I have some problem with that, because function return "undefined" – Jensej Jul 03 '17 at 15:34
  • @Jensej The program will provide the least items combination to get the sum. If there is no combination to get the target sum, `undefined` will be printed. I'll edit my answer and print "No combination found" in such case. – shaochuancs Jul 03 '17 at 23:17