Working on this code for a test, passing some but failing others.
Problem:
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a and b, check whether they are similar.
Example:
For a = [1, 2, 3] and b = [1, 2, 3], the output should be areSimilar(a, b) = true.
The arrays are equal, no need to swap any elements.
For a = [1, 2, 3] and b = [2, 1, 3], the output should be areSimilar(a, b) = true.
My Solution:
function areSimilar(a, b) {
var error = 0;
for(var i = 0; i < a.length; i++){
if(a[i] === b[i]){
return true;
} else if(a[i] !== b[i]){
error++;
}
}
if(error > 1){
return false;
} else{
return true;
}
}
Example of Test Passed:
Input:
a: [1, 2, 2] b: [2, 1, 1]
Output:
false
Expected Output:
false
Example of Test Failed:
Input:
a: [2, 3, 9] b: [10, 3, 2]
Output:
true
Expected Output:
false
Aucun commentaire:
Enregistrer un commentaire