Home > Enterprise >  Why does my code not work out well replacing strings characters?
Why does my code not work out well replacing strings characters?

Time:02-28

The exercise: The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

Examples "din" => "((("

"recede" => "()()()"

"Success" => ")())())"

"(( @" => "))(("

My code was like that:

    function duplicateEncode(word) {
      let str = "";
    
      for (let i = 0; i < word.length; i  ) { //This iteration is to examine every character in the string;
        for (let j = 0; j < word.length; j  ) { //This iteration is to compare every character to every other inside the string, in order to check if there is any repetition
          if (j === i) { //This first conditon was selected because a character is not supposed to be compared to itself
            continue;
          } else if (word[i] === word[j]) {
            str = str   ")";
            break;
          } else if (j !== word.length - 1) {
            continue;
          } else if (j === word.length - 1) {
            str = str   "(";
          } 
        }
      }
      return str;
    }

Does anyone can help me figure out why it doesn't work for all cases?

For example:

console.log(duplicateEncode("abc"));

It should return ((( instead of ((

But,

console.log(duplicateEncode("mulherm"));

returns exacly what it supposed to: )((((()

Apparently, whenever a string does not have a character that repeats,the function returns a string without the first element. But whenerver the string has at least one element that repeats it returns exacly what it's supposed to.

What is going on with my code?

CodePudding user response:

I think the issue is that when you use your snippet below, you prevent yourself from entering the last loop.

if (j === i) { 
   continue;
}

The issue is present whenever a word with a non duplicated letter is last. i.e.

This works

console.log(duplicateEncode("aba")); //returns )()

This does not

console.log(duplicateEncode("aab")); //returns ))

What you could do is add a statement that when

i === word.length - 1

and no "(" are in your str variable, you can append another ")" to your str.

In other words, if you have found no duplicated characters after checking the before last position while iterating over your entire word, the last is guaranteed to be unique as well.

Console logs below

function duplicateEncode(word) {
    let str = "";

    for (let i = 0; i < word.length; i  ) { //This iteration is to examine every character in the string;
    for (let j = 0; j < word.length; j  ) { //This iteration is to compare every character to every other inside the string, in order to check if there is any repetition
        console.log(i);
        console.log(j);
        console.log(str);
        if (j === i) { //This first conditon was selected because a character is not supposed to be compared to itself
            console.log("continue")
            continue;
        } else if (word[i] === word[j]) {
            console.log("append )")
            str = str   ")";
        break;
        } else if (j !== word.length - 1) {
            console.log("j !== length")
        continue;
        } else if (j === word.length - 1) {
            console.log("append (")
            str = str   "(";
        } 
    }
    }
    return str;
}

CodePudding user response:

Use a debugger to step through your code line by line. There are cases where the inner loop completes without ever meeting one of the conditions for a adding a character to the string.

Instead, use a boolean flag to denote whether the letter is duplicated, set that inside the loop (much simpler logic), then after the loop do str = (found ? ')' : '(');. This ensures you add exactly one character to the output string per iteration of the outer loop.

CodePudding user response:

function duplicateEncode(word) {
      let str = "";
      word = word.toLowerCase();
      for (let i = 0; i < word.length; i  ) { //This iteration is to examine every character in the string;
        let firstIndex = word.indexOf(word[i]);
        let lastIndex = word.lastIndexOf(word[i]);
        if (firstIndex === lastIndex){
          str  = "(";
        } else {
          str  = ")";
        }
      }
      return str;
}
    console.log(duplicateEncode('abc'));
    console.log(duplicateEncode("mulherm"));
    console.log(duplicateEncode('din'));
    console.log(duplicateEncode('recede'));
    console.log(duplicateEncode('Success'));
    console.log(duplicateEncode('(( @'));
    console.log(duplicateEncode('Pneumonoultramicroscopicsilicovolcanokoniosis'));

<<you don't need to loop the word string twice - deleted for technical accuracy>>javascript has built in methods to loop through a string....using the built in string.indexOf and string.lastIndexOf methods, you can simply compare if the two values are equal .... if they are equal....you character can only be in the string one time....if they are not equal your character must be in the string more than once

  • Related