1

I was doing some algorithm challenge. I am taking a number, converting it to a string then to an array and checking each of its element one by one. Code below works on javascript. The goal is that, if all of the numbers are the ones in the if statement, then the function should return true. But if there is 7 or any other value, then the function will return false.

var a = myFunction(3);

if(a === true){
    alert("true");
}
else{
    alert("false");
}
function myFunction(number){
    let array = number.toString().split("");
    
    for(var i = 0; i<array.length; i++){
        if(array[i] !== '0' && array[i] !== '1' && array[i] !== '8' && array[i] !== '5' && array[i] !== '2'){
            return false;
        }
    }
    return true;
}

I am stuck on the logic below.

if(array[i] !== '0' && array[i] !== '1' && array[i] !== '8' && array[i] !== '5' && array[i] !== '2')

Why will it not work right if I change '&&' to '||'? I am confused by the fact, if array[i] = 1, then it should be false because array[i] !== 0 or 8 or other numbers on the if statement.

5
  • what do you like to check? do you have some examples? Commented Feb 19, 2021 at 16:13
  • The goal is that, if all of the numbers are the ones in the if statement, then the function should return true. Commented Feb 19, 2021 at 16:15
  • alert(a === true) Commented Feb 19, 2021 at 16:16
  • 1
    consider (a != 1 || a != 2), if a is 1 then the "not equal to 2" part is true and the whole thing is true, even though the a != 1 part is false. Commented Feb 19, 2021 at 17:36
  • I used the exact same example to understand it. Commented Feb 20, 2021 at 20:16

2 Answers 2

1

To take logical OR || in combination with De Morgan's laws:

!(a && b) = !a || !b 
!(a || b) = !a && !b

function check(number) {
    let array = number.toString().split("");
    for (var i = 0; i < array.length; i++) {
      if (!(array[i] === '0' || array[i] === '1' || array[i] === '8' || array[i] === '5' || array[i] === '2')) {
        return false;
      }
    }
    return true;
}

console.log(check(18520));
console.log(check(7));

Sign up to request clarification or add additional context in comments.

1 Comment

Well it did not exactly answer me, but it helped me to understand it better. Thanks!
0

const inclusive = set => test => (test + '')
    .split('')
    .filter(value => set.includes(parseInt(value, 10)))
    .length > 0

let test = inclusive([0,1,2,5,8])

console.log('3: ' + test(3))
console.log('321: ' + test(321))
console.log('830: ' + test(830))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.