My code works fine except for the case at the bottom of my code, can someone please tell me why? It will be greatly appreciated!!
function mutation(arr) {
var newArray = [];
var answer;
for (var i = 0; i < arr.length; i++) {
newArray.push(arr[i].toLowerCase());
}
for (var j = 0; j < newArray[1].length; j++) {
if (newArray[0].indexOf(newArray[1][j]) === -1) {
answer = false;
}
else if (newArray[0].indexOf(newArray[1][j]) === 0) {
answer = true;
}
}
return answer;
}
mutation([âzyxwvutsrqponmlkjihgfedcbaâ, âqrstuâ]);
1 Like
I call this kind of problem the âfind a counterexampleâ problem (made that up just now). In these kinds of problems you start with the assumption that what you get is true
. Then you proceed with examining your inputs to find just one counterexample. Once you have a counterexample, you now get false
.
Typically, in code this translates to just an if-block, with no matching else block.
1 Like
Thanks! That explains why setting answer to true gets it to work! But why doesnât it work without doing so? Wouldnât it be set to true in the for loop?
Using your present code, letâs try, mutation("cats", "set")
.
You found that "s"
is found in "cats"
, so you set answer = true
.
You found that "e"
is not found in "cats"
, sou you set answer = false
. So far so good. This is the correct answer.
Then you found that "t"
is found in "cats"
, so you set answer = true
. Youâve just replaced the correct answer.
The loop completes its work and now you have answers = true
, which is definitely not true, The fate of answer
lies at the last loop iteration.
2 Likes
Ohh I see! Well setting answer to true at the top of my code. Why is that? Would you recommend adding a condition so that the loop ends when answer is set to false? Thank you so much for your responses.
1 Like
You can add break;
after setting the variable to false
, or better yetâŚ
âŚinstead of using a variable to store true
or false
, you can return false
early once the condition is met. If itâs not met at the end of the loop, then you can return true
.
function mutation(arr) {
// ...
for (...) {
if (...) {
return false;
}
}
return true;
}
2 Likes
I tried the latter method you gave (getting rid of the variable answer) but it did not work for the first case mutation(âhelloâ,âheyâ). Any ideas as to why? The following is my new code: function mutation(arr) {
var newArray = [];
for (var i = 0; i < arr.length; i++) {
newArray.push(arr[i].toLowerCase());
}
for (var j = 0; j < newArray[1].length; j++) {
if (newArray[0].indexOf(newArray[1][j]) === -1) {
return false;
}
return true;
}
}
1 Like
You were returning true
inside the for-loop. return true;
should be outside, after the loop completes.
2 Likes
Nevermind! I know why. My return true was inside of the loop.
Thank you both!
Iâm going through it now and this post has been most enlightening! You guys rock!
1 Like