what is the problem of this code? it's showing false. this should be true.
function isSpecialArray(arr) {
for(i=0; i<arr.length; i++){
return ((arr[i % 2 == 0]) % 2 == 0) && ((arr[i % 2 !==0]) % 2 !== 0)
}
}
console.log(isSpecialArray([2, 7, 4, 9, 6, 1, 6, 3])) // false??
You can simplify your code and avoid unnecessary looping as soon as the first element breaking the rule is found.
for loopfunction isSpecial(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== i % 2) return false
}
return true;
}
Array.prototype.everyfunction isSpecial(arr) {
return arr.every((item, index) => item % 2 === index % 2);
}
Your return ((arr[i % 2 == 0]) % 2 == 0) && ((arr[i % 2 !==0]) % 2 !== 0) syntax is wrong. Hope the below function meets your requirement.
Logic
isNodeSpecialisSpecial status of array.isSpecial and isNodeSpecial.isSpecial is set to false and loop exits.function isSpecialArray(arr) {
let isSpecial = true;
for (i = 0; i < arr.length && isSpecial; i++) {
const isNodeSpecial = (i % 2 === 0) ? arr[i] % 2 === 0 : arr[i] % 2 === 1;
isSpecial = isSpecial && isNodeSpecial;
}
return isSpecial;
}
console.log(isSpecialArray([2, 7, 4, 9, 6, 1, 6, 3])); // true
console.log(isSpecialArray([2, 7, 4, 10, 6, 1, 6, 3]));// false
You can check if any element does not satisfy the condition and immediately return false. If all elements satisfy the condition, then return true. That is best solution when it comes to performance. You can change your code like this:
function isSpecialArray(arr) {
for (i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== i % 2) return false;
}
return true;
}
console.log(isSpecialArray([2, 7, 4, 9, 6, 1, 6, 3])) //true
console.log(isSpecialArray([1, 7, 4, 9, 6, 1, 6, 3])) //false