Reputation: 51
There is clearly something wrong with my logic or with the logic of JS (haha).
I really don't understand why one of them works and another one doesn't.
These functions are for checking if every single index in the array is the same. The first one works, and the second one doesn't and I don't see how the logic of these two are different (besides the obvious point of changing the positions).
1.
function isUniform(x) {
var first = x[0];
for(var i = 1; i < x.length; i++) {
if(first === x[i]) {
return true;
i++;
}
} return false;
};
2.
function isUniform(x) {
var first = x[0];
for(var i = 1; i < x.length; i++) {
if(x[i] !== first) {
return false;
i++;
}
} return true;
};
Arrays used :isUniform([1, 1, 1, 2]) and isUniform([1, 1, 1, 1])
Upvotes: 1
Views: 87
Reputation: 1134
Here is a breakdown as to how your functions work on a line-by-line level (I've included comments after each statement):
function isUniform(x) {
var first = x[0]; //SET "FIRST" to first element in array
for(var i = 1; i < x.length; i++) { //loop from second element to the end
if(first === x[i]) { //if "FIRST" is equal to this element
return true; //conclude that the ENTIRE ARRAY is uniform and quit function
i++; //incremenet "i" (note, the loop automatically does this, so this will result in an extra increment
}
} return false; //conclude the array is not uniform IF THE FIRST ITEM IS UNIQUE
};
Here is a breakdown of the second function:
function isUniform(x) {
var first = x[0];//SET "FIRST" to first element in array
for(var i = 1; i < x.length; i++) { //loop from second element to the end
if(x[i] !== first) { //if this element is not equal to the first CONCLUDE THAT THE ARRAY IS NOT UNIFORM and quit function
return false;
i++; //again, extra un-needed increment, but it technically does not matter in this case
}
} return true; //CONCLUDE that since no items were NOT equal to the first item, the array is uniform
};
Thus, it should now be clear that the second array fulfills your purpose while the first one does not. Really, the first one checks if any elements other than the first are equal to the first.
Upvotes: 1
Reputation: 8589
Once you return inside a for-loop, the loop stops and the function ends.
In your first example, first will Never be equal to x[i], because you start i at 1 and first === x[0], so the loop will finish and return false.
In your second example, you'll always return false at i = 1, since x[1] !== x[0], so the loop will always return false after the first check.
Upvotes: 2