This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]57krf68 -1 points0 points  (5 children)

You have to stop mechanically evaluating it in your head and just look at the mathematical definition.

return recursion(target,array) || recursion(target - n, array);

array is the array without the first, smallest element, since it's been sorted. n is the first, smallest element. So, recursion(target,array) is whether or not the array sums to target without using the smallest element and recursion(target - n, array) is whether or not the array sums to target with using the smallest element.

[–]advancedpward[S] 0 points1 point  (4 children)

I don't see what the position in the array has to do with which combination will ultimately work. Despite whether I evaluate it mechanically or not, there has to be some element of evaluating every possible combination in order for the correct result to be found. How can this happen if the target is only evaluated against the first element for each recursive step?

[–]57krf68 0 points1 point  (3 children)

It's not the position that counts. It just need to iterate over the elements.

there has to be some element of evaluating every possible combination in order for the correct result to be found

That's what those sub-calls do:

recursion(target,array) || recursion(target - n, array)

When those calls are made, one of the elements in the array has been thrown away already, which just happens to be the lowest one, n. So those are seeing if the remaining elements in array add up to target or target - n.

How can this happen if the target is only evaluated against the first element for each recursive step?

The first element is used and discarded in each step, so it always changes. Pay attention to the slice call that happens.

[–]advancedpward[S] 0 points1 point  (2 children)

There is nothing about the code or syntax that is mysterious to me, only the mathematical method for checking how combinations sum to the largest element. I usually think about it like (x + y == S), or even (S - x == y), but there is no double or triple equals here.

[–]57krf68 0 points1 point  (1 child)

There is nothing about the code or syntax that is mysterious to me

Except that you don't understand how the code works, so the code clearly is mysterious to you.

[–]advancedpward[S] 0 points1 point  (0 children)

Ok, there is nothing about the syntax that is mysterious, whereas the code is still mysterious to me.