How to break a number into certain amounts

This variable x contains the number to be checked for the array. var x = 10; var ary = [ 3,5 ]

I want to check if x be summed up by any key combination in ary , and then show which keys add up to make x .

In this case, 3 cannot be used. Thus, the result will be = 5, 5 if x = 10 (because the function should look for the array and find that 5 + 5 is equal to 10)

The length of the array and x are unknown. I do not use libraries. Here's how far I have come so 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 that the code above is terrible, not flexible, and only works in the specific case in which I use it. How to include all possible combinations?

Assuming the array still has 2 values 3 and 5 , here are some more examples of how the result will be obtained based on x:

if x = 8 , the result will be = 3, 5 ;

if x = 15 , the result will be = 5, 5, 5

if x = 9 , the result will be = 3, 3, 3 , etc.

Note There should be no restriction on how many times the key can be used.

+5
source share
1 answer

You can use multiplication. Create an array with .length equal to the largest number inside the input ary array plus 1 , multiply the index of the array by the current number, if the product is equal to the target number, create an array having .length equal to index and fill the array with the current ary element, otherwise set the final index of the returned an array to enter a 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)); 
+2
source

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


All Articles