I have a problem to solve in JavaScript and I am not sure where to start.
I will have an array of values.
[1000, 500, 400, 300, 200, 100]
I will be given two numbers
X number of array elements to use.
N Value that the elements must add up to
Sorry but as I don’t know where to start, I do not have any attempted code to share.
Any tips on where to start would be greatly appreciated
Edit,
So for example X = 4 N = 1700,
I would want all combinations of 1700 with four elements of the array, all array elelemnts can be used as many times as required
[[1000,500,100,100], [1000,400,200,100],[1000,300,300,100],[ 500,500,500,200],[500,500,400,300],[500,400,400,490]]
No negative numbers allowed and N will always be a sum reachable with X number array elements, with no remainder,
for example X = 5, N = 6900 would never happen,
2
Answers
W3School provides some good documentation on JavaScript. In your case it’s array method. You could check it out here:
https://www.w3schools.com/js/js_array_methods.asp
I don’t really understand your problem. Some other information would be helpful for us to answer your question 😀
We can write a fairly straightforward recursion that on every step reduces some combination of the list of numbers, the count of numbers remaining, and the total sought.
There are two base cases. First, if the count is exactly zero, then we check the total: if it’s zero, then we return one empty array, and if it’s not, we return no values. Second, if our array of options is empty or if either our total or the remaining count are negative, then we return no values.
Otherwise, we concatenate two results. In the first one, we use the first entry, combining it with every result from recurring on the same array of values, a decremented count, and the difference between the total and that first entry. In the second one, we skip the first value and recur with the remaining values, the same count, and the same total.
The name "combine" is too generic, but at the moment I can’t come up with a better one.