-4

The task is the following: "Write a JavaScript program to find the shortest possible string which can create a string to make it a palindrome by adding characters to the end of it."

This is the code I am looking at:

function build_Palindrome(new_str) {
  var flag;
  for (var i = new_str.length;; i++) {
    flag = true;
    for (var j = 0; j < i - j - 1; j++) {
      if (i - j - 1 < new_str.length && new_str[j] != new_str[i - j - 1]) {
        flag = false;
        break;
      }
    }
    if (flag) {
      for (var j = new_str.length; j < i; j++) {
        new_str += new_str[i - j - 1];
      }
      return new_str;
    }
  }
}

Test:

console.log(build_Palindrome("abcddc"))

Output:

abcddcba    

My question: At first it starts with j=0. If in the for loop, flag=false, then how does it proceed? Is i=7 (i++?) and is j=0 or j=1?

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • What have you done to investigate this yourself? – tripleee Feb 27 '19 at 06:01
  • I tried to figure out how the code works. I found some articles and algorithm on Palindrome but they are for determining if the word or string of words is palindrome or not which is different. The above mentioned task looks more complicated. – Andrey Li Feb 27 '19 at 06:11
  • Why don't you simply add a few `console.log` statements in the code and examines what it shows when you run it? – tripleee Feb 27 '19 at 06:12
  • Possible duplicate of https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code – tripleee Feb 27 '19 at 06:24
  • Thank you buddy. It looks like it shows what I need. I can now investigate the code. – Andrey Li Feb 27 '19 at 15:53

1 Answers1

0

Yes, you can use console.log or any debugger to debug.

For your situation, you if the flag is false, it will break the loop of j and go to its outer loop (i here)

I made the demo here: https://repl.it/repls/LoyalProfuseRouter

You can see the demo (it come with my solution), and instead of break you can use simple loop to return your string, it more readable.

Chau Giang
  • 1,414
  • 11
  • 19