javascript - why doesn't this backtracking recursion go to other branches? -


Looking at an array, and a goal (number), I have to determine whether to attain goals by adding elements The array is my code here (in javascript), and some results:

  function check (target, array) {function add (sum, array) {if (sum == goal) return True; And if ((Yoga> Goal) || (! Array [0])) false return; Else console.log (sum); // Check where we add back (sum + array.shift (), array) || (Yoga, array); } Add return (0, array); }  

I expect the add () stack to be made after calling (6, [1,3,5])

  Add (0, [1,3,5]) // log 0 (1, [3,5]) // Add log 1 (1 + 3, [5]) // Add log 4 (1 + 3 + 5, []) // return false addition (1 + 3, []) // return false addition (1, [5]) // add log 1 (1 + 5, []) // return true return (1 (0 + 3, []) plus (0 + 3, []), ([0, [5]) plus [0, [3,5]) plus (0 + 3, [5]) plus (0 + 3, []) ) Add (0 + 5, []) (0, [])  

Add actual result:

  check (6, [1,3] , 5]]) false 0 1 4 check (3, [1,3,5]) false 0 1 1  

This is the first branch It also does not leave! Why ? Edit: Based on the suggestions, it is okay to think that the array is better as a logic to avoid:

  function check (target, Array) {function add (sum, I) {if (amount == target) is true back; And if ((Yoga> Goal) || (i == array.length)) returned incorrectly; Else console.log (sum); Return sum (zodiac + array [i], i + 1) || Adding (yoga, I + 1); } Add return (0,0); }  

This works fine.

This is the same array that has crossed all over, and after the first branch it is empty So that the recursion will be over. Try it with a copy:

  function check (target, array) {function add (sum, array) {if (sum = target) return true; And if ((Yoga> Goal) || (! Array [0])) false return; And print (zodiac); Array = array.slice (); Add return (sum + array.shift (), array) || (Yoga, array); } Add return (0, array); }  

Comments

Popular posts from this blog

Member with no value in F# -

java - Joda Time Interval Not returning what I expect -

c# - Showing a SelectedItem's Property -