Calculation of value of an additional value from an array of values

I have a numeric value and an object containing numeric values ​​with multiple keys. I need to find out which of the values ​​in the object matches the value when adding.

The only solution I could find was linear:

var values={1: 10, 2: 20, 3: 30};
var value=50;
var selected=[];

$.each(values, function(k,v){
    if(v==value)
        selected.push(k);
    $.each(values, function(k2,v2){
        if(v+v2==value) {
            selected.push(k);
        }
    });
});
console.log(selected);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run codeHide result

This works well for an object with two suitable values ​​(for example, when the value is 50). But if all three are the same (set the value to 60), this will not produce any results.

Is there any way to solve this without using a recursive function call ? If so, how?

+4
source share
2 answers

, . O(n^2) ( , , 32 ):

const results = [];

for(let i = 1; i < Math.pow(2, values.length); i++){
  const subset = values.filter((_, pos) => (i >> pos) & 1);
  if(subset.reduce((a, b) => a + b) === value)
    results.push(subset);
}
+2

. : arr . .

, : , , , .

, .

const getAllSubsets =
  theArray => theArray.reduce(
    (subsets, value) => subsets.concat(
      subsets.map(set => [value, ...set])
    ), [[]]);

const arrayOfIndexes = arr => [...Array(arr.length).keys()];

const getIndexSubsets = arr => getAllSubsets(arrayOfIndexes(arr));

// Array of int reduction function
const reduceFunctionOverIntArr = valuesArr =>
  (accumulator, currentIndex) => accumulator + valuesArr[currentIndex];

// Array of custom objs reduction function
const reduceFunctionOverObjArr = valuesArr =>
  (accumulator, currentIndex) => accumulator + valuesArr[currentIndex].val;

const checkValue = (arr, value, reduceFnc) => getIndexSubsets(arr)
  .filter(subset => subset.reduce(reduceFnc(arr), 0) === value);

const intArr = [10, 20, 30];
const customObj = [{val: 10}, {val: 20}, {val: 30}];

// Result over an int array
console.log(checkValue(intArr, 40, reduceFunctionOverIntArr));
console.log(checkValue(intArr, 50, reduceFunctionOverIntArr));
console.log(checkValue(intArr, 60, reduceFunctionOverIntArr));

// result over an object array
console.log(checkValue(customObj, 40, reduceFunctionOverObjArr));
console.log(checkValue(customObj, 50, reduceFunctionOverObjArr));
console.log(checkValue(customObj, 60, reduceFunctionOverObjArr));
Hide result
+2

Source: https://habr.com/ru/post/1694057/


All Articles