Algorithm Mutations Question

Algorithm Mutations Question
0

#1

Can someone please help me with why this code isn’t working correctly. I am new to JS so I’m sure there is a much easier way to solve this problem then the one I chose but I am coding to the best of my ability and then reviewing the better options. It runs correctly for all but one of the test cases. Thanks in advance!

function mutation(arr) {
  var arr1 = arr[0];
  var arr2 = arr[1];
  arr1 = arr1.toLowerCase().split("");
  arr2 = arr2.toLowerCase().split("");
  for (var i = 0;i < arr2.length;i++) {
    if (arr1.indexOf(arr2[i]) != -1) {
      return true;
    } else {
      return false;
    }
  }
}

mutation(["hello", "hey"]);`

#2

The reason it doesn’t work is because a return will always dump you out of the function. Since in every single case, the first letter of arr1 is present in arr2, you will always go to return true and it will dump you out of the function. the reason it matches all the other tests is that the first one ([Hello, Hey])is the only test where there is a non matching character which is not the first character. (in other words, you got lucky with the rest)

you are actually on a good track to solve it, but perhaps think about proving a negative instead of a positive? :wink:


#3

Ahhh, I see what you’re saying. Thanks alot! Got it working now!


#4

Since you got yours working and are wanting to see different solutions, here’s mine:

function mutation(arr) {
  return arr[1].toLowerCase().split('').every(function(letter){
    return RegExp(letter).test(arr[0].toLowerCase());
  });
}

#5

Would you mind walking me through your thought process on this? Looks like a foreign language to me haha.


#6

Sure. I take arr[1] and change it all to lowercase then split it into an array of characters.

Then I take the every method which takes each element of the array of characters and tests for true or false.

Inside the Array.every(callback) I convert the letter (letter in this case is the character that is being tested each time) into a RegExp which allows me to match strings.

Then I take the test method which returns true if the RegExp is found in the string being tested and test letter against arr[0] which has also been converted to lower case.

So if the test returns true (that letter from the second word is present in the first word) it goes on to the next letter and tests it. if it gets through all the letters and every one passes it returns true. but the first one that tests false, it stops testing and returns false.

so really, you can see that my code does almost the exact same thing yours does, just a different way.