1

While iterating through the for loop inside my function, even after the return statement is reached, the loop proceeds infinitely.

At this point, j is greater than lister.length. It exits the for loop and at the end of function jumps back to the for loop in a seemingly endless circuit.

This behaviour doesn't make sense to me as the return statement should terminate the function.


Here is my function:

function permutationLoop(originalArray, listOfPermutations) {

    // generates a permutation(Shuffle),and makes sure it is not already in the list of Perms
    var lister = generatingPerms(originalArray, listOfPermutations);

    //adds the permutation to the list
    listOfPermutations.push(lister);

    var tester = true;

    //This for loop looks through the new permutation to see if it is in-order.
    for (var j = 0; j < lister.length; j++) {

        //This if statement checks to see as we iterate if it is in order
        if (lister[j] > lister[j + 1]) {
            tester = false;
        }

        if (j == (lister.length - 1) && tester == true) {
            //Return the permutation number that found the ordered array.

            return listOfPermutations.length;
            //THIS IS NOT EXITING THE LOOP
        }

        if (j == lister.length - 1 && tester == false) {
            permutationLoop(originalArray, listOfPermutations);
        }
    }
}
3
  • 1
    Can you give an example of the input you're calling the function with (generatingPerms too, hopefully, because it's in the code you're using), ideally in a live snippet, so we can see how the function is running for ourselves and try to debug it? Commented Mar 9, 2019 at 6:19
  • What is generatingPerms()? Commented Mar 9, 2019 at 6:25
  • The problem is : if (lister[j] > lister[j+1]); if j is the last element, j+1 will be undefined and thus less than the last element, so tester will be set to false and the return-having IF's conditional's always false on the last element. Commented Mar 9, 2019 at 6:25

1 Answer 1

1

may your if statement is not valid try testing by if(true){ ..code.. }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.