简体   繁体   中英

Not exiting recursive function

I am writing a function which takes two lists, the second list is the same as the first, only it is shuffled and has one element removed. The function should return the missing element. I wrote this function

var findRemoved = function(firstArr, secondArr, indx){
    var indx = indx || 0;
    for(var i = 0; i<secondArr.length; i++){
        if(firstArr[indx] === secondArr[i]){
            findRemoved(firstArr, secondArr, ++indx);
        }
    }
    console.log("found end ", firstArr[indx]);
    return firstArr[indx];

}

When I run it with

var i = findRemoved([1,2,3,4,5,6,7], [5,4,2,6,1,3]);
console.log("i ",i);

I get it console logging "found end ", 7, which is correct, however the recursion doesn't break at that point and keeps on going until it returns with the answer "2" Any idea what I might be doing wrong?

Your code continues running when finds the result, so for every index keeps looping and returning that index. You can return the index that comes from the recursion, and stop looping when you have found an ocurrence of the first array in the second.

Note: I didnt try to write a good implementation, only fix yours.

var findRemoved = function(firstArr, secondArr, indx){
  var indx = indx || 0;
  var result = null;
  for(var i = 0; result==null && i<secondArr.length; i++){
      if(firstArr[indx] === secondArr[i]){
          result = findRemoved(firstArr, secondArr, ++indx);
      }
  }
  result = result || firstArr[indx]
  console.log("found end ", result);
  return result;
}

var i = findRemoved([1,2,3,4,5,6,7], [5,4,2,6,1,3]);
console.log("i ",i);

A fiddle of this: http://jsfiddle.net/b5Aus/

Have you tried something like this?

var findRemoved = function(firstArr, secondArr){
    for(var i=0, l=firstArr.length; i<l; ++i)
        if(secondArr.indexOf(firstArr[i]) < 0)
            return firstArr[i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM