Hi all,
i tried the mutation challenge with the includes( ) method. And its working fine. but there is only 1 failed case [which is …
mutation([“hello”, “hey”]) Should return false.]
and i dont know why. please help…
function mutation(arr) {
let word1 = arr[0].toLowerCase()
let word2 = arr[1].toLowerCase()
word1 = word1.split("")
word2 = word2.split("")
for ( let elem of word2)
if(word1.includes(elem)){
return true
}
else{
return false
}
}
mutation(["hello", "hey"]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
You’re getting the wrong result because you’re returning true not when ALL characters in word2 are included in word1. You are returning true (or false for that mater) if the FIRST LETTER of word2 is included in word1.
Yes, you have a loop, but you’re really just checking the FIRST elem of word2. You need to check all of them. I would try to (1) either sort the two arrays and then just check that they are identical, or (2) use some sort of hashmap or counting array to check all the letters in word1 (and then check them off when you iterate word2). There are probably other ways to do it though.
Exactly, that’s what I’ve tried to say, perhaps less eloquently than @camperextraordinaire
Remember that the key point is that you have to (1) compare ALL the characters, not just the first one, and (2) it’s not enough that one string would include all the characters of another string: It also needs to (3) include just them, and not any additional ones, and (4) they must be in the same quantity. ie, if string 1 has the letter ‘e’ twice, the second string must also include the letter ‘e’ twice, no more no less.
As you might infer, you probably need some method of counting. That’s why include probably isn’t the best way to go (not saying it’s impossible, just that it might not be enough in and of itself).
Dang you’re right. I didn’t look at the requirements too carefully when I replied. Which isn’t a good thing if one wants to be a programmer! I haven’t entirely gotten rid of the newbie habit of kinda-reading the requirements and then rushing to the solution. Still honing that all-important skill. Thanks for the correction.
@rajanisoni1 yeah, I would suggest rethinking the algorithm. Do it on pen and paper first. You’ll get it, I’m sure. If I did, most people probably could.