Reputation: 63
I've tried to write a recursive palindrom however, eventhough I reach at the end the true branch at the last iteration the return value is still undefined.
So if you type in the console my function with a palindrom. rekurzivSzigoruPalindrom("radar");
It will iterate through it perfectly but the return value, will be undefined. Could you please point out the error in my code below ? Thanks
function rekurzivSzigoruPalindrom(str, strLength = str.length) {
// debug eleje
console.log(strLength);
if (strLength > 1) {
console.log(str[str.length - strLength] + " " +str[strLength-1] );
}
if(strLength == 1){
console.log(str[str.length-1]+ " " +str[strLength-1]);
}
//debug vége
if(typeof str == "string" || typeof str == "number"){
if(typeof str == "number"){
str = str.toString();
}
if(strLength > 1){
if(str[str.length - strLength] == str[strLength-1]){
//console.log(strLength);
strLength--;
rekurzivSzigoruPalindrom(str,strLength);
}
}
else if(strLength == 1){
if(str[str.length-1] == str[strLength-1]){
console.log(strLength+"true");
return true;
}
else{
console.log(strLength+"false");
return false;
}
}
}
else {
return false;
}
}
Upvotes: 1
Views: 62
Reputation: 2804
Recursive:
function recPal(str) {
str=""+str; // for numbers
if(str.length<2) return true;
if(str[0]!=str[str.length-1]) return false;
return recPal(str.slice(1,-1));
};
var strs=[101, 75, "", "x", "xy", "99", "abba", "log", "racecar", "razor", "radar"];
strs.forEach(
word=>
console.log(
"'"+word+"'"+
(recPal(word)?" IS ":" is NOT ")+
"a palindrome"
)
);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 1156
you have to return the result of your recursive call.
function rekurzivSzigoruPalindrom(str, strLength = str.length) {
// debug eleje
console.log(strLength);
if (strLength > 1) {
console.log(str[str.length - strLength] + " " +str[strLength-1] );
}
if(strLength == 1){
console.log(str[str.length-1]+ " " +str[strLength-1]);
}
//debug vége
if(typeof str == "string" || typeof str == "number"){
if(typeof str == "number"){
str = str.toString();
}
if(strLength > 1){
if(str[str.length - strLength] == str[strLength-1]){
//console.log(strLength);
strLength--;
return rekurzivSzigoruPalindrom(str,strLength);
}
}
else if(strLength == 1){
if(str[str.length-1] == str[strLength-1]){
console.log(strLength+"true");
return true;
}
else{
console.log(strLength+"false");
return false;
}
}
}
else {
return false;
}
}
Upvotes: 1