Which is the better way to write an if condition in Smarty?
A
{if $searchCount > 0}
B
{if $searchCount}
C
{if $searchCount == 0}
D
{if !$searchCount}
It depends on what you want.
Example A:
Use this if you want to check if your $searchCount is greater than 0.
Example B:
Use this to check if your $searchCount is true. It's true if it's filled. No matter whats inside.
Example C:
This will check if $searchCount is equal to 0.
Example D:
Thats the opposite of Example B. There you check if $searchCount is false. It's false if its not filled or it's the bool false.
I hope this helps you to understand the operators.
See the PHP-Manual or W3-Schools for more informations.
Related
Let us say I have an integer array representing the chess pieces on a board;
int board[8][8];
In my chess game, I am currently coding a generator function that will return an integer vector of all legal moves.
Naturally, I will be using if statements
I am at a point where I need to check a certain element in the board relative to a piece on the board
For example, If I have a pawn piece;
board[row][col] == 'p';
I need to generate [row+1][col], [row+2][col] and in some cases if it can attack a piece, a change in column too.
But if a piece is on any edge of the board, board[row+1][col] will return be index out of range
For that reason I need an extra if statement.
My question is, shall i use:
if (pieceisnotonedge && board[row+1][col] == 0)
or
if (pieceisnotonedge)
{
if (board[row+1][col] == 0)
}
For the first example, if pieceisnotonedge returns false, will it also check the next condition? Because if it does, then I am in trouble.
For the first example, if pieceisnotonedge returns false, will it also
check the next condition?
No, it will not. Because the build-in logical operators do short-circuiting. From cppreference.com:
Builtin operators && and || perform short-circuit evaluation (do not
evaluate the second operand if the result is known after evaluating
the first), but overloaded operators behave like a regular function
calls and always evaluate both operands
Therefore, in
if (pieceisnotonedge && board[row+1][col] == 0)
if the pieceisnotonedge is false, the second will not be evaluated. Therefore, having a nested ifs is redundant, and you can go with the first version.
For the first example, if pieceisnotonedge returns false, will it also check the next condition?
No. It will "short-circuit" because if the first condition is false, checking the conditions after it is unnecessary. Read more here and here.
This is guranteed by the C++ standard:
7.6.14
... && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
Note that, for || this is opposite, that is, if the first condition is "true", then checking the conditions afterwards is unnecessary
Shall i use; or...
Both are same, if you have a short if statement (with only two conditions), I would suggest using the first approach. In terms of efficiency there is no difference and you can verify this by looking at the generated assembly for both cases on godbolt
For the shown code there is no difference, both board[row+1][col] == 0 are only evaluated if pieceisnotonedge is true.
If you should use one or the other, cannot be said be in general, as it depends on other factors (like semantic, readability, …) too.
If you e.g. want to have an action that it done if either pieceisnotonedge or board[row+1][col] == 0 is false, then you probably would use &&, because then you can write:
if (pieceisnotonedge && board[row+1][col] == 0) {
} else {
// do something else
}
with your other style you would need to write:
if (pieceisnotonedge){
if (board[row+1][col] == 0) {
// do something else
}
} else {
// do something else
}
In general, your first aim should be to have readable code. While pieceisnotonedge && board[row+1][col] == 0 easy to read, more complex expressions might not be. So you would decide that on a case by case basis, if you want to use one expression or multiple if.
For the first example, if pieceisnotonedge returns false, will it also check the next condition?
No. It will stop immediately after pieceisnotonedge is evaluated to false. There is no subsequent check for the remainder condition board[row+1][col] == 0
You can use nested if as the second code as well - no difference. It's just a matter of what code would look clearer.
while(a!=1&&c!=1)
{
r=rand()%2;
if(r==0)
{
cout<<"Cruz"<<endl;
if(a==1)
{
c=0;
}
c++;
}
else if(r==1)
{
if(a>1)
{
a=0;
}
cout<<"Cara"<<endl;
a++;
}
b++;
}
I don't know why but this loop always exits when one of the two conditions is false... and I need when both are false.
Does anyone know why is this happening?
pretty sure you want an || instead of a && because you want it to continue if either of them are true statements. (alternatively, and this would be probably more coherent, you could do:!(a==1||c==1))
The logical and operation only returns true when both the conditions are met. If you require the loop to work please use the logical OR operator that returns true when any one of the conditions are met. Please see the below truth table. Please check if you are using the correct logical operator
After the while statement, you explain the condition that must stay true while the code continues to loop. Since you want to exit when a and b have some property, you need to keep looping while either a or b does not have that property.
Say you can't go to sleep until both your homework and your chores are done. That means you need to stay awake while either your homework or your chores aren't done.
At the moment I´m testing around with particles and have one important question.
if (condition a || condition b || condition c)
or
if(condition a)
if(condition b)
if(condition c){
}
Which is faster?
C++ uses what is known as short-circuit expression evaluation, which means that as soon as it encounters a term which determines the final result of the expression, (regardless of what the remaining terms may evaluate to,) it will stop evaluating terms.
Since TRUE OR X is TRUE regardless of the value of X, C++ will not bother evaluating X.
However, your cascaded if statement is not equivalent to the first expression. It is equivalent to an expression with multiple ANDs not multiple ORs.
This has likely been answered somewhere else before, but C++ uses the short circuit method, that is, if any condition passes, the rest are ignored (in the case of logical or: |).
The reverse is true for logical and: & - the first condition that fails short circuits the if statement and it exits early.
Here's an example:
if (condition a || condition b || condition c) {
// This code will execute if condition a is true, condition a or b is true, or if all three are true
}
if (condition a && condition b && condition c) {
// This code will only execute if all three are true, but if a is false, it will exit early, the same can be said for b
}
I want to overwrite some elements of a vector x with a scalar a based on a 0/1 vector cond. In pseudocode: x[cond]=a.
x[cond] is not the right way of subsetting in Mata. I should use select(x,cond). Unfortunately, this latter object cannot be assigned to.
x[selectindex(cond)] = a fails because such an assignment requires the same dimensions on both sides of the =.
I could modify the latter approach to
x[selectindex(cond)] = J(sum(cond),1,a)
Is that the idiom in Mata? I was expecting something more straightforward because Stata has nice replace x = a if cond syntax.
In the general case, I think that's about as good as you're going to get. sum(cond) is safe if cond is 0 or 1, but a more general alternative is:
select = selectindex(cond)
x[select] = J(length(select), 1, a)
I agree that this is not the simplest syntax. An additional assignment colon operator := would be nice here.
If x and cond are views, st_store() is another option:
st_store(., st_viewvars(x), st_viewvars(cond), J(sum(cond), 1, a))
If you already know the variable names/indices and don't have to call st_viewvars(), all the better.
I need to understand how this recursion work, I understand simple recursion examples but more advanced ones is hard. Even thought there are just two lines of code I got problem with... the return statement itself. I just draw a blank on how this works, especially the and/or operator. Any insight is very welcome.
bool subsetSumExists(Set<int> & set, int target) {
if (set.isEmpty()) {
return target == 0;
} else {
int element = set.first();
Set<int> rest = set - element;
return subsetSumExists(rest, target)
|| subsetSumExists(rest, target - element);
}
}
Recursive code is normally coupled with the concept of reduction. In general, reduction is a means to reduce an unknown problem to a known one via some transformation.
Let's take a look at your code. You need to find whether a given target sum can be constructed from an elements of the input data set.
If the data set is empty, there is nothing to do besides comparing the target sum to 0.
Otherwise, let's apply the reduction. If we choose a number from the set, there can actually be 2 possibilities - the chosen number participates in the sum you're seeking or it doesn't. No other possibilities here (it's very important to cover the full spectrum of possibilities!). In fact, it doesn't really matter which data element is chosen as long as you can cover all the possibilities for the remaining data.
First case: the number doesn't participate in the sum. We can reduce the problem to a smaller one, with data set without the inspected element and the same target sum.
Second case: the number participates in the sum. We can reduce the problem to a smaller one, with data set without the inspected element and the requested sum decreased by the value of the number.
Note, you don't know at this point whether any of these cases is true. You just continue reducing them until you get to the trivial empty case where you can know for sure the answer.
The answer to the original question would be true if it's true for any of these 2 cases. That's exactly what operator || does - it will yield true if any of its operands (the outcome of the 2 cases) are true.
|| is logical OR. It's evaluated left-to-right and short-circuited.
This means that in an expression A || B, A is evaluated first. If it's true, the entire expression is true and no further evaluation is done. If A is false, B is evaluated and the expression gets the value of B.
In your example, A is "try getting the same sum without using the 1st element from the set". B is "use the 1st element from the set, which decreases the total left to sum, and try to get that with the rest of the element."
Lets first look at algorithm..
The base case(i.e the case in which recursion terminates) is when the set is empty.
Otherwise the program takes the first elements subtracts it from the set.
Now it will call subsetSumExists(rest, target) and check if its true,
if it is it will return true otherwise it will call
subsetSumExists(rest, target - element) and return whatever it
returns.
In simple terms, it will this call subsetSumExists(rest, target - element) only if first one subsetSumExists(rest, target) returns false.
Now lets try to dry run this code with a small sample set of {3,5} and a sum of 8. I'll call the function sSE from now on
sSE({3,5}, 8) => "sSE({5}, 8) || sSE({5},(8-3))"
sSE({5}, 8) => sSE({}, 8) || sSE({}, (8-5))
sSE({}, 8) => false.. now will call sSE({}, (8-5))
sSE({}, 3) => false.. now will call sSE({5}, (8-3))
sSE({5}, 5) => sSE({}, 5} || sSE({}, (5-5))
sSE({}, 5) => false.. now will call sSE({}, (5-5))
sSE({}, 0) => true.. ends here and return true
To understand recursion, you need to understrand recursion.
To do that, you need to think recusively.
In this particular case.
For any: subsetSum(set, target)
If set is empty AND target is 0, then subsetSum exists
Otherwise, remove first element of the set. check if subdetSum(set, target) exists OR subdetSum(set, target - removed_element) exists (using step 0)
The set subtraction looks a strange syntax but I will assume it means pop() on the element.
It "works" through finding every possible combination although it is exponential.
In the || statement, the LHS is the sum including the current element and the RHS is the sum excluding it. So you will get, down the exponential tree, every combination of each element either switched on or off.
Exponential, by the way, means that if you have 30 elements it will produce 2 to the power of 30, i.e. 0x40000000 or close to a billion combinations.
Of course you may well run out of memory.
If it finds the solution it might not run through all 2^N cases. If there is no solution it will always visit them all.
If I speak for myself, difficulty in understanding of the problem stems from || operator. Let's glance at bottom return statement of same code with another way,
if (subsetSumExists(rest, target - element))
return true;
if (subsetSumExists(rest, target))
return true;
return false;