Vitali Halaveika
Vitali Halaveika

Reputation: 51

Why here I got different results?

I have next task: Given an array of ints, return true if the array contains no 1's and no 3's.

First version and it's right:

for (int i = 0; i < nums.length; i++){
    if(nums[i] == 1 || nums[i] == 3)
        return false;
}
return true;

but here's I got many wrong tests:

for (int i = 0; i < nums.length; i++) {
    if (nums[i] != 1 || nums[i] != 3)
        return true;
}
return false;

Can you explain me reason why does it work like this? I supposed reason is something happened in second if(...)

Upvotes: 0

Views: 71

Answers (4)

Zabuzard
Zabuzard

Reputation: 25903

The code should return true if there are no 1s and no 3s.

Let us take a look at your second code:

// Iterate all values
for (int i = 0; i < nums.length; i++) {
    // Return true if value is not 1 OR not 3
    if (nums[i] != 1 || nums[i] != 3)
        return true;
}

// Return false
return false;

The key here is the condition val != 1 || val != 3 which is a tautology, i.e. it is true in all cases. Suppose a value of 5, it is not 1, so true is returned. Now suppose a value of 1, it is 1 but it is not 3, also true is returned.

You would need to substitute || by && which means and, which also better reflects your textual condition:

return true if the array contains no 1's and no 3's

However you can not directly return true if you found the first element which is not 1 and not 3. You first need to check all elements. However you can directly return false if you found the first 1 or 3. And that is exactly the first version of your code, which is correct.


Note that when negating a conditions you need to negate all quantifiers and operators too.

The first code realizes an approach using this logic:

  • Not (there exists one element which is 1 or 3)
  • ¬(∃ e : e = 1 ∨ e = 3)

When now solving the negation you receive this logic:

  • All elements are not 1 and not 3
  • ∀ e : e ≠ 1 ∧ e ≠ 3

So (exists) turns to (for all), = to and (or) to (and).

Upvotes: 2

Kinshuk Lahiri
Kinshuk Lahiri

Reputation: 1500

For the second answer, you are using OR instead of AND. Hence whatever value you provide, it will always enter into the if condition.

Hope this helps.

Upvotes: 0

jrtapsell
jrtapsell

Reputation: 7001

Why the first one works

It returns false if any item is not 1 or 3, and true if no items match

Why the second one does not work

It returns true all the time (if any item is not equal to 1 or 3, and no integer is equal to both 1 and 3), the only way to get false is to pass it an empty array.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311228

You're implementing a short-circuit evaluation. The first version is right. In the second version, you prematurely return true when you encounter a number that isn't 1 or 3 - which is every number, since 1 is not 3 and vise versa.

Upvotes: 0

Related Questions