Basic Algorithm Scripting - Mutations

Hi.
Been Struggling with this one. I appreciate the code probably isn’t the cleanest, but it worked other than on the [“Voodoo”, “no”] check. I added the splice line in line 14 to remove letters as they’re matched to avoid multiple matches on the ‘o’. But now it fails on the [“Mary”, “Aarmy”] check and I’ve no idea why.

Any help greatly appreciated.

  **Your code so far**
function mutation(arr) {
let newArr = arr.map(function (lower) {
  return lower.toLowerCase();
});
let check = 0;
let a = newArr[0].split('');
let b = newArr[1].split('');
for (let i = 0; i < a.length; i++){
  for( let z = 0; z < b.length; z++){
    //console.log(a);
    //console.log(b);
    if (a[i] === b[z]){
      check += 1;
      b.splice (z, 1);
    }
  }
  

}
if (check >= arr[1].length){
      return true
    } else {
      return false;
    }
}

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

console.log(mutation(["Mary", "Aarmy"]))
  **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

Challenge: Basic Algorithm Scripting - Mutations

Link to the challenge:

Let’s format this for readability:

function mutation(arr) {
  let newArr = arr.map(function (lower) {
    return lower.toLowerCase();
  });
  let check = 0;
  let a = newArr[0].split('');
  let b = newArr[1].split('');

  for (let i = 0; i < a.length; i++) {
    for (let z = 0; z < b.length; z++) {
      //console.log(a);
      //console.log(b);
      if (a[i] === b[z]) {
        check += 1;
        b.splice(z, 1);
      }
    }
  }

  if (check >= arr[1].length) {
    return true
  } else {
    return false;
  }
}

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

console.log(mutation(["Mary", "Aarmy"]))

You are mutating b as you iterate over it. That will create very confusing results, because your index z (most people use j in that spot) will no longer reference the same variable.

I would absolutely avoid mutating an array as you iterate over it.

ahh Thanks so much for your reply. I had since solved it inn far fewer lines using indexOf() method but just couldn’t understand why this earlier attempt failed only on [“Mary”, “Aarmy”]. Learnt not to mutate an array whilst iterating over it though so thanks.

Any help with why it fails on the one example. Appreciate everyone’s busy busy. Just trying to understand (and hopefully learn from) the error.

This check is faulty.

You can fix the logic by not tearing apart b, reordering your loops, and stopping the inner loop when you find a match.

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