user6597020
user6597020

Reputation:

How to break apart a number by specific sums

This variable x contains a number that needs to be tested against an array. var x = 10; var ary = [ 3,5 ]

I want to test if x can be made up by the sum of any combination of the keys in ary, then show what keys do add up to make x.

In this case the 3 cannot be used. So the result would = 5, 5 if x = 10 ( because the function should search the array and find that 5 + 5 equals 10 )

The length of the array and x are not known. I'm not using any libraries. This is how far I've come thus far:

var x = 10;
var ary = [ 3, 5 ];

function cycle(){
  var result;
  for( var i = 0; i < ary.length; i++ ){
    if( ary[ i ] + ary[ i ] == x ){
       result = ary[ i ] + ',' + ary[ i ];
    }
    else if( ary[ i ] + ary[ i + 1 ] == x ){
      result = ary[ i ] + ',' + ary[ i + 1 ];
    }
    else if( ary[ i + 1 ] + ary[ i + 1 ] == x ){
      result = ary[ i + 1 ] + ',' + ary[ i + 1 ];
  }
  return result;
  }
}
  

var result = cycle();
document.write( result );

I know the above code is terrible, not flexible in the least, and only works in that particular case I use it for. How would I include all possible combinations?

Assuming the array still only has the 2 values 3 and 5, here are more examples how what result would get based on x:

if x = 8, result would = 3, 5;

if x = 15, result would = 5, 5, 5

if x = 9, result would = 3, 3, 3 etc.

Note: There should be no limit to how many times a key can be used.

Upvotes: 5

Views: 378

Answers (1)

guest271314
guest271314

Reputation: 1

You can use multiplication. Create an array having .length equal to the greatest number within input array ary plus 1, multiply the index of the array by the current number, if the product equals target number, create an array having .length equal to index and fill the array with current element of ary, else set resulting index of returned array to input number.

const x = [8, 9, 10, 15];
let ary = [3, 5];

let nums = (n, arr) => {
  let [keys, res] = [
    Array.from(Array(Math.max.apply(Math, arr) + 1).keys()).splice(1)
    , Array()
  ];
  for (let prop of arr) {
    for (let index of keys) {
      if (prop * index <= n) {
        if (prop * index === n) {
          res.push(Array(index).fill(prop)); break;
        }
      } else {
        res.push(prop); break;
      }
    }
  }
  return {x:n, result:res};
}

for (let num of x) console.log(nums(num, ary));

Upvotes: 2

Related Questions