1

I am a beginner in java-script. I am writing code that returns true or false for palindrome string. I know there are lot of ways to write code to check palindrome yet I want to know what went wrong in my code. please help.

function palindrome(str) {

  if (str == "") {
    return false;
  } else {
    const palia = str.replace(/[\W_]/g, "").toLowerCase();
    const number = palia.length;
    console.log(number);
    var num1 = number / 2;
    num1 = Math.floor(num1);
    console.log(num1);

    for (var i = 1; i < num1; i++) {
      var b = number - i;
      b++;
      console.log(b);
      if (palia[i] == palia[b]) {
        console.log("Ture");
        return true;

      } else {
        console.log("false");
        alg = "false";
        return false;
      };
    };
  };

};

console.log(palindrome("eye"));

And I know i have written lengthy code. My apologies. I will learn other ways to write. But this is exiting with code=0. at for loop. Please help. Thanks in advance.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    I really don't get what you are trying to accomplish. Maybe would be best if you analyze other people's solutions while you are learning, until you get the hang of it (and still, is something to keep doing even when you are an expert) https://stackoverflow.com/questions/22111507/how-to-write-palindrome-in-javascript – alotropico Jul 13 '20 at 23:58

5 Answers5

0

There are many problems with that code

  • in loop start indexing from 0
  • you can iterate only to half string
  • "" actually is palindrome
gkucmierz
  • 1,055
  • 1
  • 9
  • 26
  • 1
    It's correct to iterate only to half string. You only have to test if all elements in the first half match the corresponding element in the second half. – Barmar Jul 14 '20 at 00:00
0

I've commented the lines I replaced below.

function palindrome(str) {

    if (str == ""){
        // Empty string is a palindrome
        // return false;
        return true;
    } else {
        const palia = str.replace(/[\W_]/g, "").toLowerCase();
        const number = palia.length;
        console.log(number);
        var num1 = number / 2;
        num1 = Math.floor(num1);
        console.log(num1);
    
        // Must compare from the first position
        //for (var i = 1; i < num1; i++){
        for (var i = 0; i <= num1; i++){
            var b = number - i;
            // Increment gives out of bound access
            //b++;
            b--;
            console.log(b);
    
            if (palia[i] == palia[b]){
                // Typo
                //console.log("Ture");
                console.log("True");
                return true;
    
            } else{
                console.log("false");
                alg = "false";
                return false;
                
            };
        };
    };         
};
    
palindrome("eye");
Carlos Bazilio
  • 830
  • 9
  • 20
0

On the case of "eye" the for loop is not executed at all, because 1 is not smaller but the same size as the length of num1.

0

You need to start the loop at index 0, not 1.

You shouldn't return true as soon as you find a match, because there can be mismatches later. Instead, return true if you get to the end of the loop without finding a mismatch.

Your calculation of b is wrong, it should be number - i - 1, not number - i + 1. For instance, if the length of the string is 6, you must compare element 0 with 5, 1 with 4, and 2 with 3.

There's no need to check for an empty string. This is a palindrome, and the loop will correctly detect this (the loop will stop immediately, so it falls through to return true).

function palindrome(str) {

  const palia = str.replace(/[\W_]/g, "").toLowerCase();
  const number = palia.length;
  console.log(number);
  var num1 = number / 2;
  num1 = Math.floor(num1);
  console.log(num1);

  for (var i = 0; i < num1; i++) {
    var b = number - i - 1;
    console.log(b);
    if (palia[i] == palia[b]) {
      console.log("True");
    } else {
      console.log("False");
      return false;
    }
  }
  return true;
};

console.log(palindrome("eye"));
console.log(palindrome("abcdefg"));
console.log(palindrome("abcdeedcba"));
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Should be like:

function palindrome(str, insensitive = true){
  let s = str.split(''), l = s.length, i = Math.floor(l/2), a = s.slice(0, i), b, r;
  if(l % 2 !== 0)i++;
  b = s.slice(i); b.reverse(); b = '^'+b.join('')+'$';
  r = insensitive ? new RegExp(b, 'i') : new RegExp(b);
  if(a.join('').match(r)){
    return true;
  }
  return false;
}
console.log(palindrome('eyes'));
console.log(palindrome('eye'));
console.log(palindrome('noon'));
console.log(palindrome('none'));
console.log(palindrome('Nun'));
console.log(palindrome('Nun', false));
StackSlave
  • 10,613
  • 2
  • 18
  • 35