Reputation: 51
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
Reputation: 25903
The code should return true
if there are no 1
s and no 3
s.
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:
1
or 3
)¬(∃ e : e = 1 ∨ e = 3)
When now solving the negation you receive this logic:
1
and not 3
∀ e : e ≠ 1 ∧ e ≠ 3
So ∃
(exists) turns to ∀
(for all), =
to ≠
and ∨
(or) to ∧
(and).
Upvotes: 2
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
Reputation: 7001
It returns false if any item is not 1 or 3, and true if no items match
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
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