Problem with first test example for Mutations exercise

Tell us what’s happening:
Describe your issue in detail here.
There are a dozen of tests in this algorithm test and they all return correctly true or false, except the first one:
mutation(["hello", "hey"]) should return false .

I don’t understand why this is the case and hopefully someone can clear it up for me. Thanks!

  **Your code so far**

function mutation(arr) {
let str0 = arr[0].toLowerCase();
let str1 = arr[1].toLowerCase();
let unique = '';
for (let i = 0; i < str0.length; i++){
   if(unique.includes(str0[i]) === false){
     unique += str0[i];
   }
}
for (let j = 0; j < str1.length; j++){
   if(unique.includes(str1[j]) === false){
     return false;
   } 
   return true;
}
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36

Challenge: Mutations

Link to the challenge:

Try to follow step-by-step what happens in the code, specifically second loop. In the troublesome test, what’s the str1, what’s the str[0], is it in the unique? What happens if yes and what happens if not?

1 Like

I see. It’s just lucky that my code had almost all correct answers. If I now understand my code correctly, second loop was just checking if the first letter is included, not if the entire string is. That’s why for hello and hey, it returned true, instead of false.

2 Likes

first, your logic is a bit stretched and there are some unnecessary actions. All you need to do is loop thru every letter in the second string and see if its part of the first string.
Where your function fail is, your second loop return value from the function too soon. A return statement within a loop will exit the function which the loop is part of and return the given value. Your loop does not run all its course(does not look thru all letters) when the function should return true. As soon as it determines the first letter is included, your function returns true and does not check the remaining letters

1 Like

Thanks! I edited my function and now it works like it should. Removed unique, cuz its unnecessary, I thought I’ll need that approach at the beginning. Another change is that I lowered return true line. Does the job now!

function mutation(arr) {

let str0 = arr[0].toLowerCase();

let str1 = arr[1].toLowerCase();

for (let i = 0; i < str1.length; i++){

   if(str0.includes(str1[i]) === false){

     return false;

    } 

  }

  return true;

}

mutation(["hello", "hey"]);
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.