Mutations Challenge

Mutations Challenge
0

#1

Need some insight with Mutations Challenge

function existsMoreThanOnce(array, element) {
    var counter = 0;
    for (var i = 0; i < array.length; i++) {
      if (element === array[i])
        ++counter;
    }
    return counter;
}

function mutation(arr) {
  var mainWord = arr[0].toLowerCase().split("");
  var secondaryWord = arr[1].toLowerCase().split("");
  var matchedLetters = [];
  var counter = 0;
  
  
  // Loop through main word
  for (var i = 0; i < mainWord.length; i++) {
    // Loop through second array
    for (var j = 0; j < secondaryWord.length; j++) {
      // If element of the mainWord matches the element of the second array
      if (mainWord[i] === secondaryWord[j]) {
        // If the element is not in matchedLetters array
        if (matchedLetters.indexOf(mainWord[i]) === -1) {
          // If the matched element exists more than once in the mainWord array
          if (existsMoreThanOnce(mainWord, mainWord[i]) > 1 && existsMoreThanOnce(secondaryWord, secondaryWord[j]) > 1) {
            // Then push that element existed times
            for (var k = 0; k < existsMoreThanOnce(mainWord, mainWord[i]); k++) {
              matchedLetters.push(mainWord[i]);
              ++counter;
            }
          } else {
            matchedLetters.push(mainWord[i]);
            ++counter;
          }
        }
      }
    }
  }
  
  if (counter == secondaryWord.length)
    return true;
  
  // Else
  return false;
  
  
}

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


#2

mutation([“Mary”, “Aarmy”]) should return true. This is the only condition I can’t pass.


#3

its failing because its looking for two a in Mary not for if Mary contains the letter a … eg if you change Aarmy to Army it passes Aarmy could have 10 letter a and should pass eg Mary Aaaaaaaaaarmy should pass.

think of it like this … first letter in Aarmy … a … has Mary an a true … second letter in Aarmy … a … has Mary an a true
now that in code could look something like below (well before they were split() )

 if( secondaryWord.idexOf(mainWord(charAt(i) ===  -1) {
       return false;
   }

#4

I shared on a slack channel and an engineer solved it I can’t stop admiring how clean and short it is :smiley:

function mutation(arr) {
  var first = arr[0].toLowerCase();
  var second = arr[1].toLowerCase();
  var missingChars = second.split('').filter(char => first.indexOf(char) === -1);
  return Boolean(!missingChars.length);
}