Best Practice to Avoid Too Many If Statements in ios - ios

You all might have came across the scenarios like the following ones:
-(int) fightMath(int one, int two) {
if(one == 0 && two == 0) { result = 0; }
else if(one == 0 && two == 1) { result = 0; }
else if(one == 0 && two == 2) { result = 1; }
else if(one == 0 && two == 3) { result = 2; }
else if(one == 1 && two == 0) { result = 0; }
else if(one == 1 && two == 1) { result = 0; }
else if(one == 1 && two == 2) { result = 2; }
else if(one == 1 && two == 3) { result = 1; }
else if(one == 2 && two == 0) { result = 2; }
else if(one == 2 && two == 1) { result = 1; }
else if(one == 2 && two == 2) { result = 3; }
else if(one == 2 && two == 3) { result = 3; }
else if(one == 3 && two == 0) { result = 1; }
else if(one == 3 && two == 1) { result = 2; }
else if(one == 3 && two == 2) { result = 3; }
else if(one == 3 && two == 3) { result = 3; }
return result;
}
In short, how to effectively simplify the above scenario in Objective-C's ambience?
Any Suggestions/Ideas/Solutions ?
Cheers :)
Edit: For reference , scenario taken from here.I hope this question might save even one sec of needy developer.

Objective C is built over C. So any good C solution will be also appropriate for Objective C. Like
int result[][4] = {
{ 0, 0, 1, 2 },
{ 0, 0, 2, 1 },
{ 2, 1, 3, 3 },
{ 1, 2, 3, 3 }
};
return result[one][two]
As I know there is no Objective C - specific good practices for such problems.

Related

Is there any arithmetic formula that can test all given numbers are in row, like [ 3 5 4 ]

I m making a card game where 3 random numbers are generated..I need to check are these numbers Row numbers...
like 4 6 5 and 23,24,22. are row numbers
I have made method but I think there should be easy arithmetic formulas
I have tried this and working well, but I need simple arithmatic formula to avoid use of array and for
bool isAllInRow(int num1, int num2,int num3)
{
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
for(int x=0;x<numbers.length-1;x++)
{
if(numbers[x]-numbers[x+1]!=-1)
{
is_in_row=false;
break;
}
}
return is_in_row;
}
So you want to know if the cards form a straight, with aces both low and high.
Is the "three cards" fixed, or would you want to generalize to more cards?
Sorting should be cheap for such a short list, so that's definitely a good start. Then you just need to check the resulting sequence is increasing adjacent values.
I'd do it as:
bool isStraight(List<int> cards) {
var n = cards.length;
if (n < 2) return true;
cards.sort();
var first = cards.first;
if (first == 1 && cards[1] != 2) {
// Pretend Ace is Jack if n == 3.
// Accepts if remaining cards form a straight up to the King.
first = 14 - n;
}
for (var i = 1; i < n; i++) {
if (cards[i] != first + i) return false;
}
return true;
}
This code rejects card sets that have duplicates, or do not form a straight.
I think you are looking for Arithmetic Progression.
bool checkForAP(List<int> numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
if (numberArr[2] - numberArr[1] != diff) {
return false;
}
return true;
}
And modify your function like
bool isAllInRow(int num1, int num2,int num3) {
//subject : tinpati
List<int> numbers=[num1,num2,num3];
bool is_in_row=true;
numbers.sort();
if(numbers[0]==1 && numbers[1]==12 && numbers[2]==13)
return true;
return checkForAP(numbers);
}
Note: remove sort in AP method as it is of no use. Since your numbers
list length is 3 I directly compared numbers for AP, the same can also
be written for n numbers with for.
bool checkForAp(numberArr) {
numberArr.sort();
int diff = numberArr[1] - numberArr[0];
for(int i = 2; i< numberArr.length ;i++) {
if (numberArr[i] - numberArr[i - 1] != diff) {
return false;
}
}
return true;
}
You could do it like this:
bool isAllInRow(int num1, int num2,int num3) {
if (num1 == num2 || num2 == num3) return false;
var maxNum = max(num1, max(num2, num3));
var minNum = min(num1, min(num2, num3));
return (maxNum - minNum == 2) || (minNum == 1 && maxNum == 13 && num1 + num2 + num3 == 26);
}

How to use a Ternary Operator with multiple condition in flutter dart?

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);
}

Is it possible to show the real slippage when orderSend()

For MT4,MQL
When sendOrder(),
It sometimes successes or sometimes misses mainly because of slippage.
I would like to get the real slippage when sendOrder().
Is it possible???
My source code for now is like this below.
Ticket = OrderSend(_Symbol,OP_SELL, Lot,Bid,2, // '2' is slippage alloable limit.
SL,TP,comment,Magic);
if (Ticket > 0){
// if slippage is under 2 it works.
// want to check the real slippage
}
else {
int err = GetLastError();
if(err == ERR_NO_ERROR ||
err == ERR_COMMON_ERROR ||
err == ERR_SERVER_BUSY ||
err == ERR_NO_CONNECTION ||
err == ERR_TRADE_TIMEOUT ||
err == ERR_INVALID_PRICE ||
err == ERR_PRICE_CHANGED ||
err == ERR_OFF_QUOTES ||
err == ERR_BROKER_BUSY ||
err == ERR_REQUOTE ||
err == ERR_TRADE_CONTEXT_BUSY){
//want to check the slippage here!!!
}
}
You have to calculate slippage on your own by subtracting the OrderOpenPrice from the price you sent with the order.
Example:
double price = Bid;
double slippage = 0.0;
int ticket = OrderSend(_Symbol, OP_SELL, Lot, price, 2, SL, TP, comment, Magic);
if(OrderSelect(ticket, SELECT_BY_TICKET))
slippage = int(NormalizeDouble(fabs(price - OrderOpenPrice()) / _Point, 0));

Swift optional multiple tests in conditional

I want to do something like this with an optional in swift.
var opt:MyOptional?
func myfunction() {
if (opt == nil) || (opt?.x != 10 && opt?.y != 20)) {
opt = MyOptional()
opt.x = 10
opt.y = 20
}
}
My question is if this is a valid pattern, even though it compiles and runs. Does Swift compiler ensures condition 2 runs after condition 1 (opt!= nil)?
Well && and || operators in swift are Left Associative which means your evaluation of conditions goes from left hand side.
(opt != nil). // result 1
this condition will get evaluate first and as you are using the || operator.
Secondaly your (opt?.x != 10 && opt2?.y != 20) // result 2
will get now evaluate if your result 1 is false otherwise it would have gone in the loop because of || operator
final condition
if (result 1 || result 2) {
if only result 1 is true it not evaluate for result 2 due to || operator otherwise it would calculate result 2 and if result 2 is true its a success
Assuming you have got a typo this code should looks like this:
struct MyOptional {
var x: Int = 0
var y: Int = 0
}
class SomeClass {
var opt: MyOptional?
func myFunction() {
if let unwrappedOpt = opt,
unwrappedOpt.x != 10 && unwrappedOpt.y != 20 {
opt = MyOptional(x: 10, y: 20)
}
}
}
What about your question? You are right.

Find if point(lattitude,longtitude) is inside area

I have points(lat,long) coordindates and i have area leftTop(lat,long) rightBottom(lat,long) , i need to check if my points is inside area.
It's not correct just to check if point coordinate is more than leftLat, and less rightLat.
I have corners
leftLat=81.49021937827182
leftLng=38.979793936014175
rightLat=-0.5414380758487521
rightLng=173.9797962829470
function rayCrossesSegment($point, $a, $b)
{
$px = $point['lng'];
$py = $point['lat'];
$ax = $a['lng'];
$ay = $a['lat'];
$bx = $b['lng'];
$by = $b['lat'];
if ($ay > $by) {
$ax = $b['lng'];
$ay = $b['lat'];
$bx = $a['lng'];
$by = $a['lat'];
}
// alter longitude to cater for 180 degree crossings
if ($px < 0) {
$px += 360;
};
if ($ax < 0) {
$ax += 360;
};
if ($bx < 0) {
$bx += 360;
};
if ($py == $ay || $py == $by) {
$py += 0.00000001;
}
if (($py > $by || $py < $ay) || ($px > max($ax, $bx))) {
return false;
}
if ($px < min($ax, $bx)) {
return true;
}
$red = ($ax != $bx) ? (($by - $ay) / ($bx - $ax)) : INF;
$blue = ($ax != $px) ? (($py - $ay) / ($px - $ax)) : INF;
return ($blue >= $red);
}

Resources