irrespective of the values, the if block is executing in C# - c#-3.0

if (updateYN.ToUpper() != Constants.NO
|| updateYN.ToUpper() != Constants.N)
{
// execute code for any other updateYN
}
I am trying to perform a filtration that if the value of updateYN is not NO(Constants.NO) or N(Constants.N), then execute the statement.
But the problem is that, irrespective of the values, the if block is executing.

It seems like you want an AND statement...no? (NOT NO AND NOT N)

Logically think about it this way:
your statement breaks down into three components
a = updateYN.ToUpper() != Constants.NO
b = updateYN.ToUpper() != Constants.N
c = a or b
But if you think about it, if updateYN.ToUpper() is Constants.NO then a is false, but b is true, and thus c is true. And if updateYN.ToUpper() is Constants.N then b is false, but a is true, and thus c is true. What you seem to want is
if(updateYN.ToUpper() != Constants.NO && updateYN.ToUpper() != Constants.N)
This means that updateYN.ToUpper() must equal something other than Constants.NO and Constants.N in order for the entire statement to be true.

OK, your problem is you are translating language to code. Your statement should be:
if (updateYN.ToUpper() != Constants.NO
&& updateYN.ToUpper() != Constants.N)
{
// execute code for any other updateYN
}
This tells the compiler that updateYN.ToUpper() should not be NO and should not be N.
EDIT: To make it more clear why your if condition is always getting concluded, here is some explanation. Imagine this statement:
if (x != 1 || x != 2)
{
...
}
You would imagine that if x is 1 or 2, the block shouldn't be executed, but it WILL, because this statement consists of two parts actually:
x != 1
x != 2
The or part tells the compiler that if any of these conditions is true, then the whole condition is true. Obviously, if x is 1, then it is not 2, so the condition is fulfilled, and same thing if it is 2. Think of all the values in the world, they can't be equal to 1 and 2, so this block will always get executed. Same with your case here. Hope that explains your problem well.

If Constants.NO and Constants.N are not equal, this is always true. It is probably always different from either NO or N.

Related

Trying to understand if statements in Scala

I am trying to understand why my code doesn't work! I am trying to solve the classic balance parentheses problem and Im getting a no such element on my third if statement which doesn't make sense to me because I thought my second if statement would avoid that case but I dont think my second if statement is returning?
def balance(chars: List[Char]): Boolean = {
def check(left: Int,right: List[Char]): Boolean = {
if (left < 0) false
if (right.isEmpty) left == 0
if (right.head == ')') check(left + 1, right.tail)
else check(left - 1, right.tail)
}
check(0,chars.filter(x => (x == ')') || (x == '(')))
}
Following up on my comment. I don't believe that you are actually getting a Null Pointer exception. Scala doesn't encourage the use of nulls and I don't know of any case where the standard library will return a null. Nulls are encapsulated by Option.None in Scala (or see upcoming explicit nulls in Scala 3) and even when you are integrating with a Java library, it is recommended that you wrap the null behavior in an option.
That being said, under the assumption that you are getting a No Such Element Exception in reality, let's look at you code.
Understanding the return behavior in Scala
A Scala function will take the last value in it's body as it's return value. In your case it is this block
if (right.head == ')') check(left + 1, right.tail)
else check(left - 1, right.tail)
Since the previous if blocks are not conditionally linked together all 3 of them will be evaluated. Even if one of the first two evaluates the true, Scala will NOT return and continue to evaluate because it sees more code in the function body it has not computed yet.
So in this case even if the second condition is true, the third one still gets evaluated.
Use the full ternary syntax and add else
if (left < 0) false else
if (right.isEmpty) left == 0 else
if (right.head == ')') check(left + 1, right.tail)
else check(left - 1, right.tail)
More on ternary syntax here
Let us desugar check definition a little bit:
def check(...) =
{
if (left < 0) false else (); // expression 1
if (right.isEmpty) left == 0 else (); // expression 2
return if (right.head == ')') check(...) else check(...); // expression 3 (last expression)
}
Note how the semicolons ; make it clear we have three separate expressions in the expression block, and only the last one is passed to return. Now the two key concepts to understand are
conditional expressions if (𝑒1) 𝑒2 else 𝑒3 are first-class values (and not control statements)
the "returned" value of the whole block expression is only the value of the last expression in the block
Hence to fix the issue, as suggested by others, we need to connect the three separate expressions into a single expression of the form if...else if ... else if ... else.

Why does this if statement give an output despite the && conditions not being satisfied?

I have been trying to execute a piece of code with some if conditions. This is a simple version of it.
X=100;Y=100;
if ((((X+1) && (Y+1))<=99) && (((X+1) && (Y+1))<=102))
disp(X);
end
Despite both X and Y not satisfying the first condition, I still get the output as 100. I have tried all combinations of & and && to make the and operations in the work. I checked the difference between the two and I found that & is a logical bit-wise operator while && is a short-circuit operator, which probably doesn't change much in this context. What's the error with this syntax?
Of course the code works when I do this:
X=100;Y=100;
if (X+1)<=99 && (Y+1)<=99 && (((X+1) && (Y+1))<=102)
disp(X);
end
But this is so inefficient when there are lot of conditions and each sub-condition must include the constraints. I'm sure this must be answered somewhere and this question might be a duplicate, so please point me to the answer.
So it looks like you understand what (X+1)<=99 && (Y+1)<=99 does. Let's look at ((X+1) && (Y+1))<=99:
&& requires a logical value on each side. a && b will turn a and b into logicals, effectively becoming a~=0 && b~=0. Thus:
((X+1) && (Y+1) ) <= 99
((X+1)~=0 && (Y+1)~=0) <= 99
( true && true ) <= 99
1 <= 99
true
Of course the truth value of (X+1)~=0 and (Y+1)~=0 could be different, but here you see this. In MATLAB, true is equal to 1 in a non-logical context, as when compared to 99.
If you want to simplify this expression, use max instead of &&:
X=100;Y=100;
if max(X+1,Y+1)<=99 && max(X+1,Y+1)<=102
disp(X);
end
If the max of a and b is smaller than 99, then both a and b are smaller than 99.
(Obviously, the statement can be further simplified to if max(X+1,Y+1)<=102, since if the second inequality holds than so must the first.)

How do I determine if *exactly* one boolean is true, without type conversion?

Given an arbitrary list of booleans, what is the most elegant way of determining that exactly one of them is true?
The most obvious hack is type conversion: converting them to 0 for false and 1 for true and then summing them, and returning sum == 1.
I'd like to know if there is a way to do this without converting them to ints, actually using boolean logic.
(This seems like it should be trivial, idk, long week)
Edit: In case it wasn't obvious, this is more of a code-golf / theoretical question. I'm not fussed about using type conversion / int addition in PROD code, I'm just interested if there is way of doing it without that.
Edit2: Sorry folks it's a long week and I'm not explaining myself well. Let me try this:
In boolean logic, ANDing a collection of booleans is true if all of the booleans are true, ORing the collection is true if least one of them is true. Is there a logical construct that will be true if exactly one boolean is true? XOR is this for a collection of two booleans for example, but any more than that and it falls over.
You can actually accomplish this using only boolean logic, although there's perhaps no practical value of that in your example. The boolean version is much more involved than simply counting the number of true values.
Anyway, for the sake of satisfying intellectual curiosity, here goes. First, the idea of using a series of XORs is good, but it only gets us half way. For any two variables x and y,
x ⊻ y
is true whenever exactly one of them is true. However, this does not continue to be true if you add a third variable z,
x ⊻ y ⊻ z
The first part, x ⊻ y, is still true if exactly one of x and y is true. If either x or y is true, then z needs to be false for the whole expression to be true, which is what we want. But consider what happens if both x and y are true. Then x ⊻ y is false, yet the whole expression can become true if z is true as well. So either one variable or all three must be true. In general, if you have a statement that is a chain of XORs, it will be true if an uneven number of variables are true.
Since one is an uneven number, this might prove useful. Of course, checking for an uneven number of truths is not enough. We additionally need to ensure that no more than one variable is true. This can be done in a pairwise fashion by taking all pairs of two variables and checking that they are not both true. Taken together these two conditions ensure that exactly one if the variables are true.
Below is a small Python script to illustrate the approach.
from itertools import product
print("x|y|z|only_one_is_true")
print("======================")
for x, y, z in product([True, False], repeat=3):
uneven_number_is_true = x ^ y ^ z
max_one_is_true = (not (x and y)) and (not (x and z)) and (not (y and z))
only_one_is_true = uneven_number_is_true and max_one_is_true
print(int(x), int(y), int(z), only_one_is_true)
And here's the output.
x|y|z|only_one_is_true
======================
1 1 1 False
1 1 0 False
1 0 1 False
1 0 0 True
0 1 1 False
0 1 0 True
0 0 1 True
0 0 0 False
Sure, you could do something like this (pseudocode, since you didn't mention language):
found = false;
alreadyFound = false;
for (boolean in booleans):
if (boolean):
found = true;
if (alreadyFound):
found = false;
break;
else:
alreadyFound = true;
return found;
After your clarification, here it is with no integers.
bool IsExactlyOneBooleanTrue( bool *boolAry, int size )
{
bool areAnyTrue = false;
bool areTwoTrue = false;
for(int i = 0; (!areTwoTrue) && (i < size); i++) {
areTwoTrue = (areAnyTrue && boolAry[i]);
areAnyTrue |= boolAry[i];
}
return ((areAnyTrue) && (!areTwoTrue));
}
No-one mentioned that this "operation" we're looking for is shortcut-able similarly to boolean AND and OR in most languages. Here's an implementation in Java:
public static boolean exactlyOneOf(boolean... inputs) {
boolean foundAtLeastOne = false;
for (boolean bool : inputs) {
if (bool) {
if (foundAtLeastOne) {
// found a second one that's also true, shortcut like && and ||
return false;
}
foundAtLeastOne = true;
}
}
// we're happy if we found one, but if none found that's less than one
return foundAtLeastOne;
}
With plain boolean logic, it may not be possible to achieve what you want. Because what you are asking for is a truth evaluation not just based on the truth values but also on additional information(count in this case). But boolean evaluation is binary logic, it cannot depend on anything else but on the operands themselves. And there is no way to reverse engineer to find the operands given a truth value because there can be four possible combinations of operands but only two results. Given a false, can you tell if it is because of F ^ F or T ^ T in your case, so that the next evaluation can be determined based on that?.
booleanList.Where(y => y).Count() == 1;
Due to the large number of reads by now, here comes a quick clean up and additional information.
Option 1:
Ask if only the first variable is true, or only the second one, ..., or only the n-th variable.
x1 & !x2 & ... & !xn |
!x1 & x2 & ... & !xn |
...
!x1 & !x2 & ... & xn
This approach scales in O(n^2), the evaluation stops after the first positive match is found. Hence, preferred if it is likely that there is a positive match.
Option 2:
Ask if there is at least one variable true in total. Additionally check every pair to contain at most one true variable (Anders Johannsen's answer)
(x1 | x2 | ... | xn) &
(!x1 | !x2) &
...
(!x1 | !xn) &
(!x2 | !x3) &
...
(!x2 | !xn) &
...
This option also scales in O(n^2) due to the number of possible pairs. Lazy evaluation stops the formula after the first counter example. Hence, it is preferred if its likely there is a negative match.
(Option 3):
This option involves a subtraction and is thus no valid answer for the restricted setting. Nevertheless, it argues how looping the values might not be the most beneficial solution in an unrestricted stetting.
Treat x1 ... xn as a binary number x. Subtract one, then AND the results. The output is zero <=> x1 ... xn contains at most one true value. (the old "check power of two" algorithm)
x 00010000
x-1 00001111
AND 00000000
If the bits are already stored in such a bitboard, this might be beneficial over looping. Though, keep in mind this kills the readability and is limited by the available board length.
A last note to raise awareness: by now there exists a stack exchange called computer science which is exactly intended for this type of algorithmic questions
It can be done quite nicely with recursion, e.g. in Haskell
-- there isn't exactly one true element in the empty list
oneTrue [] = False
-- if the list starts with False, discard it
oneTrue (False : xs) = oneTrue xs
-- if the list starts with True, all other elements must be False
oneTrue (True : xs) = not (or xs)
// Javascript
Use .filter() on array and check the length of the new array.
// Example using array
isExactly1BooleanTrue(boolean:boolean[]) {
return booleans.filter(value => value === true).length === 1;
}
// Example using ...booleans
isExactly1BooleanTrue(...booleans) {
return booleans.filter(value => value === true).length === 1;
}
One way to do it is to perform pairwise AND and then check if any of the pairwise comparisons returned true with chained OR. In python I would implement it using
from itertools import combinations
def one_true(bools):
pairwise_comp = [comb[0] and comb[1] for comb in combinations(bools, 2)]
return not any(pairwise_comp)
This approach easily generalizes to lists of arbitrary length, although for very long lists, the number of possible pairs grows very quickly.
Python:
boolean_list.count(True) == 1
OK, another try. Call the different booleans b[i], and call a slice of them (a range of the array) b[i .. j]. Define functions none(b[i .. j]) and just_one(b[i .. j]) (can substitute the recursive definitions to get explicit formulas if required). We have, using C notation for logical operations (&& is and, || is or, ^ for xor (not really in C), ! is not):
none(b[i .. i + 1]) ~~> !b[i] && !b[i + 1]
just_one(b[i .. i + 1]) ~~> b[i] ^ b[i + 1]
And then recursively:
none(b[i .. j + 1]) ~~> none(b[i .. j]) && !b[j + 1]
just_one(b[i .. j + 1] ~~> (just_one(b[i .. j]) && !b[j + 1]) ^ (none(b[i .. j]) && b[j + 1])
And you are interested in just_one(b[1 .. n]).
The expressions will turn out horrible.
Have fun!
That python script does the job nicely. Here's the one-liner it uses:
((x ∨ (y ∨ z)) ∧ (¬(x ∧ y) ∧ (¬(z ∧ x) ∧ ¬(y ∧ z))))
Retracted for Privacy and Anders Johannsen provided already correct and simple answers. But both solutions do not scale very well (O(n^2)). If performance is important you can stick to the following solution, which performs in O(n):
def exact_one_of(array_of_bool):
exact_one = more_than_one = False
for array_elem in array_of_bool:
more_than_one = (exact_one and array_elem) or more_than_one
exact_one = (exact_one ^ array_elem) and (not more_than_one)
return exact_one
(I used python and a for loop for simplicity. But of course this loop could be unrolled to a sequence of NOT, AND, OR and XOR operations)
It works by tracking two states per boolean variable/list entry:
is there exactly one "True" from the beginning of the list until this entry?
are there more than one "True" from the beginning of the list until this entry?
The states of a list entry can be simply derived from the previous states and corresponding list entry/boolean variable.
Python:
let see using example...
steps:
below function exactly_one_topping takes three parameter
stores their values in the list as True, False
Check whether there exists only one true value by checking the count to be exact 1.
def exactly_one_topping(ketchup, mustard, onion):
args = [ketchup,mustard,onion]
if args.count(True) == 1: # check if Exactly one value is True
return True
else:
return False
How do you want to count how many are true without, you know, counting? Sure, you could do something messy like (C syntax, my Python is horrible):
for(i = 0; i < last && !booleans[i]; i++)
;
if(i == last)
return 0; /* No true one found */
/* We have a true one, check there isn't another */
for(i++; i < last && !booleans[i]; i++)
;
if(i == last)
return 1; /* No more true ones */
else
return 0; /* Found another true */
I'm sure you'll agree that the win (if any) is slight, and the readability is bad.
It is not possible without looping. Check BitSet cardinality() in java implementation.
http://fuseyism.com/classpath/doc/java/util/BitSet-source.html
We can do it this way:-
if (A=true or B=true)and(not(A=true and B=true)) then
<enter statements>
end if

MATLAB logical operators: && vs &

If I want to ensure that an if statement only executes if BOTH of two conditions are true, should I be using & or && between the clauses of the statement?
For example, should I use
if a == 5 & b == 4
or
if a == 5 && b == 4
I understand that the former is elementwise and the latter is capable of short-circuiting but am not clear on what this means.
For a scalar boolean condition I'd recommend you use &&. Short-circuiting means the second condition isn't evaluated if the first is false, but then you know the result is false anyway. Either & or && one will be true only if both sides of the expression are true, but & can return a matrix result if one of the operands is a matrix.
Also, I believe in Matlab comparisons should be done with ==, not with = (assignment).

Unable to add a condition to a while loop in Matlab

I have a while loop which looks like this:
while ((min_t_border>0) && (colided_border_num > 0) && (~(min_t>0)))
...
end
I want to add to it another condition: (exit_border_point ~= false) or (exit_border_point)
when I put ether of the conditions above in an if statement it works. But when I try to add it as an additional condition to the while, or even when I try to add another condition to the if, for example I've tried if ((exit_border_point ~= false) && (true)) it tells me:
"Operands to the || and && operators must be convertible to logical scalar values."
What am I doing wrong?
*exit_border_point gets ether a (3x1) vector or false
Since exit_border_point can be a vector, try using the any or all functions, like this:
if (~any(exit_border_point))
As you can probably guess, any returns true if anything in the array evaluates to true and all returns true if everything in the array is true. They're kind of like vector equivalents to || and &&.
For the condition to make sense in the context of an if or while statement, it should evaluate to a scalar.
Thus, you should write
all(exit_border_point)
(which is equivalent to all(exit_border_point == true)), if you want true if all are true. Replace all with any if you want to exit the while-loop as soon as any exit_border_point is true.
Note that && and || only work for scalars. They're short-cut operators in that the second statement won't be evaluated if the first one determines the outcome (e.g. evaluates to false in case of &&. If you want to element-wise compare arrays, use & and |.
If exit_border_point is a 3x1 vector then (exit_border_point ~= false) also returns a 3x1 vector, hence the error. Use this condition instead:
~isequal(exit_border_point, false)