I am trying to check to find out whether or not numberOfItemsPerSection is bigger than 3 in the if condition. It always returns true. Then I decided to debug.
How is it possible that indexPath.row equals to 1 and numberOfItemsPerSection = 20 and it goes into to the if condition.
What am I doing wrong by using the following ternary operator?
if(indexPath.row == (numberOfItemsPerSection > 3) ? (numberOfItemsPerSection-4) : numberOfItemsPerSection)
{
}
Use parenthesises to resolve priority. Change the condition by below way. Just cover your turnery condition with parenthesis. It will resolve the turnery operator first and then it will compare it to indexPath.row.
if(indexPath.row == ((numberOfItemsPerSection > 3) ? (numberOfItemsPerSection-4) : numberOfItemsPerSection))
NSInteger desiredRow = numberOfItemsPerSection > 3 ? (numberOfItemsPerSection-4) : numberOfItemsPerSection;
if(indexPath.row == desiredRow) { ... // do your coding }
You can write:
if (indexPath.row == (numberOfItemsPerSection > 3 ? numberOfItemsPerSection - 4 : numberOfItemsPerSection)) { ... }
Or if you don't want to hurt your eyes:
BOOL desiredRow = numberOfItemsPerSection > 3 ? numberOfItemsPerSection - 4 : numberOfItemsPerSection;
if (indexPath.row == desiredRow) { ... }
Related
I have been trying to implement the shunting yard algorithm, but the output of my parser is incorrect.
let mut stack: Vec<String> = vec![];
let mut op_stack: Vec<String> = vec![];
for current in sub_tree {
if current.tok_type == TokenType::NUMBER || current.tok_type == TokenType::NEGNUMBER {
self.parse();
stack.push(current.content.clone());
}
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
}
The original equation I am parsing: 1 + 2 * 3
I expected the following output: 1 2 3 * +
Instead I get this: 1 2 3 + *
I think I am going wrong somewhere in my while loop but I don't really know. I tried to follow the example on the Wikipedia article.
I forgot I had to pop from the operator stack back into the output stack at the end.
Comparing your code
if current.tok_type == TokenType::SUBBIN
|| current.tok_type == TokenType::PLUSBIN
|| current.tok_type == TokenType::DIVBIN
|| current.tok_type == TokenType::MULBIN
{
while op_stack.len() > 0 && op_stack.last().unwrap().to_string() != "(" {
if op_prec(&op_stack.last().unwrap().to_string()) > op_prec(¤t.content)
|| (op_prec(&op_stack.last().unwrap().to_string()) == op_prec(¤t.content)
&& op_asso(¤t.content) == "left")
{
stack.push(op_stack.pop().unwrap().to_string());
} else {
break;
}
}
op_stack.push(current.content.to_string())
}
with the Wikipedia code https://en.wikipedia.org/wiki/Shunting-yard_algorithm
- an operator o1:
while (
there is an operator o2 other than the left parenthesis at the top
of the operator stack, and (o2 has greater precedence than o1
or they have the same precedence and o1 is left-associative)
):
pop o2 from the operator stack into the output queue
push o1 onto the operator stack
It looks like they are functionally identical.
So I suspect the problem is not with the code, but instead with the precedence table. If you have the precedence of + and * the wrong way round, then you would get this behaviour. It is easy to get this mixed up as some source have precedence going from tighter binding to loser one and some have the opposite. Compare Wikipedia order of operations and Operator Precedence in Java, use the former.
how to use ternary if else with two or more condition using "OR" and "AND" like
if(foo == 1 || foo == 2)
{
do something
}
{
else do something
}
i want to use it like
foo == 1 || foo == 2 ? doSomething : doSomething
If you're referring to else if statements in dart, then this ternary operator:
(foo==1)? something1():(foo==2)? something2(): something3();
is equivalent to this:
if(foo == 1){
something1();
}
elseif(foo == 2){
something2();
}
else something3();
For three conditions use:
value: (i == 1) ? 1 : (i == 2) ? 2 : 0
Try below
(2 > 3)?print("It is more than 3"):print("It is less than 3");
////Prints It is less than 3 to the console
For AND try this,
// here both or multiple conditions needs to satisfy
if (primaryImageUploaded == true && signatureImageUploaded == true) {
// status bool condition in true
} else {
// if false
}
For OR try this,
// here need ONLY any one condition to satisfy
if (primaryImageUploaded == true || signatureImageUploaded == true) {
// status bool condition in true
} else {
// if false
}
Another Dart Syntax
if (100 > 50) {
print("100 is greater than 50");
}
it is easy,
if(foo == 1 || foo == 2)
{
do something
}
{
else do something
}
it can be written thus for OR statement
foo==1 || foo==2 ? do something : else do something
it can be written thus for AND statement
foo==1 && foo==2 ? do something : else do something
both will work perfectly
EDITED
The original answer has run a little bit of from the question asked. Below is my edited answer.
To use ternary operator
(foo == 1 || foo == 2) ? doSomething() : doSomethingElse();
For my cleaner approach
{1, 2}.contains(foo) ? doSomething() : doSomethingElse();
ORIGINAL
The cleaner way for me is
if ({1, 2}.contains(foo)) {
//do something
} else {
//do something else
}
Here is an example of the same
Text((managerStatus == "pending")
? "Requested"
: (adminStatus == "confirm")
? "Amount credited"
: "Admin Pending")
Try this:
foo == 1 ? doSomething1 : (foo == 2 ? doSomething1 : doSomething2)
If you have to include multiple conditions then you should use parantheses
Simple Multiple check in one condition
if(in_array($foo, [1,2,'other'])) {
//do something
}
else {
//else do something
}
void main(){
var a,b,c,d;
a = 7;
b = 9;
c = 11;
d = 15;
print((a>b)?((a>c)?((a>d)?a:d):c):(b>c)?((b>d)?b:d):(c>d)?c:d);
}
This is the loop in my app:
for var i = column - 1; i >= 0 && burgers[i, row]?.burgerType == burgerType;
i -= 1, horzLength += 1 {
}
What would be the best way to implement this loop in Swift 2.2.1?
Try this:
var i = column - 1
while i >= 0 && burgers[i, row]?.burgerType == burgerType {
i -= 1
horzLength += 1
}
This sort of abuse of the for loop syntax was the exact reason it was deprecated in Swift 2.2. Even if a for syntax was available, this would still be more clear than that abomination
I am new to programming and trying to find a simpler way to do this:
if state[0] != 0 && state[1] != 0 && state[2] != 0 && state[3] != 0 && state[4] != 0 && state[5] != 0 && state[6] != 0 && state[7] != 0 && state[8] != 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
I tried the code below but it reacted like a OR rather than a AND.
if state[0&1&2&3&4&5&6&7&8] != 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
Thanks for any help!
Assuming that your intention is to check if all array elements
are different from zero, the easiest approach would be
if !state.contains(0) { ... }
Your code
if state[0&1&2&3&4&5&6&7&8] != 0 { ... }
does not work
as intended because here the bitwise AND 0&1&2&3&4&5&6&7&8
is computed first (with result zero), so that is equivalent to
if state[0] != 0 { ... }
let state = [0,1,2,0,4,5,6,7]
if state.filter{$0 != 0}.count > 0 {
gameOverLabel.text = "It's a tie."
gameOverLabel.hidden = false
active = false
}
Try this one
The general case with an Array of indices
The short version
let indices = [4,2,9,6,5,3,8,0]
if !indices.contains({ state[$0] == 0 }) {
// ...
}
A second version which only shows the possibilities of Swift:
if !indices.lazy.map{ state[$0] }.contains(0) {
// ...
}
The lazy is used since otherwise map would apply the closure to all indices whereas lazy applies it on average only to half the elements (contains determines the number of executions of the closure).
Note: There is probably no performance improvement for a small amount of indices. The first version is certainly (ever so slightly) faster.
A specific range of indices
Just use the approach above with
let indices = 5...9
Or directly operate on the sub sequence of Array which is ArraySlice.
Side note: Even though it seems that ArraySlice (return type of Array[Range<Int>]) is a value type, internally it is a reference type (like Array) which only copies itself on mutation. In addition ArraySlice is only a view into the array (as long none of them is mutated). So it could be even faster than the first approach.
if !state[24...42].contains(0) {
// ...
}
Good morning. Sorry for the indelicate question, but how to create an expression that is not greater than 2 and less than 1 in Objective C
My code dosn't work
if([(UIPinchGestureRecognizer*)sender scale]<=2.0 || [(UIPinchGestureRecognizer*)sender scale]>=1.0)
|| is the operator for logical OR, which isn't what you want. You need &&, the operator for logical AND.So now your code will look like this:
if([(UIPinchGestureRecognizer*)sender scale]<=2.0 && [(UIPinchGestureRecognizer*)sender scale]>=1.0)
Let's break that down...
an expression that is not greater than 2
if (! (someValue > 2)) {
// someValue is not greater than 2
}
However, "not greater than 2" is the same thing as "less-than-or-equal to 2" so...
if (someValue <= 2) {
// someValue is not greater than 2
}
Now, for the second part...
an expression that is less than 1
if (someValue < 1) {
// someValue is less than 1
}
And...
an expression that is not greater than 2 and less than 1.
if ((someValue <= 2) && (someValue < 1)) {
// someValue is not greater than 2 and less than 1
}
However, if you think about it, any number that is less than 1 will also be "not greater than 2" so you don't even need that part.
if (someValue < 1) {
// someValue is less than 1... and it is also not greater than 2
}