I'm trying to learn recursion on my own and have come across an exercise that asks: " Write a recursive function that determines whether an array is a palindrome, where the array and its size are given as parameters. Returns 1 if a[] is a palindrome, 0 otherwise."
I've tried a lot of things, but my code is still not working. I am accessing the console.log check in the last section of code, but the x, y, and stepsLeft variables do not appear to update. (WARNING:)The code is, therefore, an unclosed loop and either the maximum call stack size is exceeded or the code recurses infinitely. Help in fixing it?
function isPalindrome(arr, size) {
var stepsLeft;
var x;
var y;
// initialize variables that will change in subsequent calls
if (stepsLeft === undefined) {
var hold = size / 2;
stepsLeft = Math.floor(hold);
x = 0;
y = size - 1;
}
logged = console.log(stepsLeft);
//base case: if you go through all steps towards the center and everything matches, return true
if (stepsLeft === 0) {
return 1;
}
//recursion cases
if (arr[x] !== arr[y]) {
// if the x and y EVER don't match, return false.
return 0;
}
//increase the x and decrease the y, and check again
x++;
y--;
stepsLeft--;
console.log("here");
return isPalindrome(arr, size);
}
arr,size) passed in toisPalindromenever actually change, so each timeisPalindromeis called, it runs exactly the same way. For the recursion to work, you'll want to solve part of the problem and then callisPalindromewith the smaller remaining problem.