Mutations Help with repeated characters

Mutations Help with repeated characters
0

#1
  var t=arr[0];
  var l=arr[1];
  var temp=[];
  
  t=t.toUpperCase();
  l=l.toUpperCase();
  
  for(var i=0; i<l.length; i++){
    for(var j=0; j<t.length; j++){
     
      if(l[i]==t[j]){
      
       temp.push("t[j]");
       
       }
         
    }
  
  }
 
  var x=temp.length;
  var y=arr[1].length;
  
  if(x!=y){
    return false;
  }
  else return true;
  
  
}

#2

Do you have a question? (Also, you should really format your code to make it easier to read)


#3

The code works except when the string repeats characters. Also how do I format the code(i thought it was done automatically)?


#4

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#5

What are you trying to accomplish with the above code? What do you think it is doing?


#6

if the character at position i in array l is in the other array push it into the temp array.


#7

You need to put some console.log statements into your code, so you can see what you are actually pushing into temp. The following line is going to push the string “t[j]” into temp when the if statement is true.

temp.push("t[j]");

Even if you figure out the correct way to add the character to temp array, then if one of the words has duplicate letters of the other word, it will double count them, because of your if statement and nested for loops.

For example, in the test case mutation([“hello”, “Hello”]), each “l” in “hello” will match both “l” characters in “Hello”, so temp would look like [ ‘H’, ‘E’, ‘L’, ‘L’, ‘L’, ‘L’, ‘O’ ] and when the following codes runs, temp.length (7) gets assigned to x and arr[1].length (5) gets assigned to y and since x and y will not be equal, your function will return false.

  var x=temp.length;
  var y=arr[1].length;
  
  if(x!=y){
    return false;
  }
  else return true;

#8

Thanks for the help. What you described is exactly what i’m asking about (hence help with repeated characters). I am asking if there is a simple solution with what i have above or if a different strategy would be easier.


#9

Let me share a very basic algorithm written in pseudo-code using your variable names. See if can rewrite your code to use the following logic. You had a variable named t which was arr[0] and a variable named l which was arr[1]. I have renamed t to be checkWordr and l to be searchFor to make it clearer what each of these array element’s really represent.

#1) Iterate through each letter of searchFor and check if each letter is in checkWord.

#2) If a letter in searchFor is not found in checkWord return false.

#3) If all letters in searchFor have been traversed, this means all letters were found, so return true.