Algorithm Scripting, Mutations

Tell us what’s happening:

Hi guys. i 'm sure there is more elegant/shorter way to get done with this, i just cant get to that. Anyway most of requirements checks expect last one as i assumed, because it count every “o” . And when i try to test “===” with my ending if statement then hello fails because it has more than the length of second word. Is there way just to count letters that repeat just once, L for example, or something like that, i mean is there solution for this code, or i should try something else?

ps. Sorry for reposting same question already asked, just wanted to check if somehow my code can be “fixed”.
Your code so far


function mutation(arr) {
  let counter = 0;                         //  ----for later check

  let temp1 = arr.slice(0, 1).join().toLowerCase();     //  ----- string-ing, lowerCase-ing
  let temp2 = arr.slice(1, 2).join().toLowerCase();

  for (let i = 0; i < temp2.length; i++) {            //    ----- loops, checking letters and "adding" ones that exist
    for (let j = 0; j < temp1.length; j++) {      
      if (temp2.charAt(i) === temp1.charAt(j)) {
        counter++;
      }
    }
  }

  if (counter >= temp2.length) {                           // ----- checking if it has  enough to pass true
    return true;
  }
  else {
    return false;
  }

}

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

Solved with:

function mutation(arr) {
  let word1 = arr[0].toLowerCase();
  let word2 = arr[1].toLowerCase();
  
  for (let i = 0; i < word2.length; i++) {
    if (!word1.includes(word2[i])) {
      return false;
    }
  }
  return true;
}

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations

I was stuck on this one for far to long.
Don’t make the same mistake as me and put a if else statement inside the loop.
only return true if the if statement has no false O.o

1 Like