I am writing a program in which I use an if statement to check some condition; if true I increment a counter. The problem is that as soon as the statement is true the variable either gets incremented endlessly or by random number.
I have been trying to use some clause to break out of this statement if condition meet but with no luck
my code:
if(res_vect_angle >=60 && res_vect_angle <=100 && left_mag_b >100)
{
//line(drawing, *iter_s, *(iter_s -1), Scalar( 255, 255, 255 ), 2,8 );
left_hook_count++;
cout<<"Left Hook:..........................!!! "<<left_hook_count<<endl;
if(left_hook_count++ == true)
{
break;
}
}
The whole chunk of code associated with the issue:
float M1, M2;
float A1, A2;
double left_mag_a, left_mag_b;
double res_vect_angle;
int i = 0;
for(vector<Point>::iterator iter_lh = Leftarm.begin(); iter_lh != Leftarm.end(); ++iter_lh)
{
if(iter_lh->y <=240 && iter_lh->y >=60 && iter_lh->x >=340 && iter_lh->x <=680)
{
left_detect.push_back(*iter_lh);
if(i % 4 == 0)
{
if(left_detect.size()>4)
{
for(vector<Point>::iterator iter_s = left_detect.begin()+3; iter_s != left_detect.end(); ++iter_s, i++)
{
//Resultant Magnetude
M1 = pow((double) iter_s->x + (iter_s -2)->x,2);
M2 = pow((double) iter_s->y + (iter_s -2)->y,2);
left_mag_a = (M1 + M2);
left_mag_b = sqrt(left_mag_a);
//Resultant Angle
A1 = abs(iter_s->x - (iter_s -2)->x);
A2 = abs(iter_s->y - (iter_s -2)->y);
res_vect_angle = abs(atan2(A1,A2) * 180 /PI);
//cout<<"LEFT HOOK ANGLE IS: "<<res_vect_angle<<endl;
if(res_vect_angle >=60 && res_vect_angle <=100 && left_mag_b >100)
{
//line(drawing, *iter_s, *(iter_s -1), Scalar( 255, 255, 255 ), 2,8 );
left_hook_count++;
cout<<"Left Hook:..........................!!! "<<left_hook_count<<endl;
if(left_hook_count++ == true)
{
break;
}
}
}
}
}
}
}
Hope this helps guys ps. left_hook_count++; is a int variable declared on top of my main().
The best solution is probably to invert the test, and make all the rest of the outer if conditional:
if (whatever) {
// do some stuff
if (left_hook_count != true) { // or whatever the test should really be
// do some more stuff
}
}
You could get the program flow you want using goto with a label after the outer if, but you don't want to.
On the other hand, it sounds like perhaps this is in a loop, and you don't want to enter the if block at all if the counter has been incremented? In that case you want:
if (left_hook_count == 0 && whatever) {
// do some stuff
}
you could provide more details so that we can figure out whats happening.
You might not have initialized it?
and checking again
if(left_hook_count++ == true)
it will increment it again unneccessariy and for for first count (0 : it wont happen)
i guess you 're using some recursive function. so check for Break condition (all test cases too).
Don't compare left_hook_count++ to true. In this context, true is equal to 1, and once left_hook_count exceeds 1, this test will fail and the code will never hit the break.
And you don't break out of an if statement. You break out of a loop; a break in an if statement inside the loop is one way of doing this.
You can just negate the condition, instead of trying to break out of the if:
if(...) {
if(!left_hook_count++) {
// Do what you need to do
}
}
my new answer:
:mylabel if (some_condition)
{
//code
if (some_condition) {break mylabel;}
//code
}
my old answer: Replace the if statement with a while statement containing a unconditional break at the end.
(old answer was before I learned of attaching labels to statement blocks.)
In your case:
while(res_vect_angle >=60 && res_vect_angle <=100 && left_mag_b >100)
{
//line(drawing, *iter_s, *(iter_s -1), Scalar( 255, 255, 255 ), 2,8 );
left_hook_count++;
cout<<"Left Hook:..........................!!! "<<left_hook_count<<endl;
if(left_hook_count++ == true)
{
break;
}
break; //this unconditional break makes the while loop act as an if statement
}
However if you don't have code after the conditional break what's the point of having it? I'm assuming you've omitted that code? The way you wrote it it would simply break out of the inner for loop.
Related
the printOptimalAlignment function is misbehaving. goto and return will not exit when the function reaches location (1,1)... where it should end, no crash and it stops at seemingly an arbitrary location of (6,6)... because for some reason it increments at the end of the function even though there is no increment-er for the values int yL, int xL, (but I don't follow why it calls itself if it gets to the end of the function without any "hits" on the if statements.
Full code:
https://repl.it/#fulloutfool/Edit-Distance
void printOptimalAlignment(int** arr, string y, string x,int yL, int xL){
int I_weight=1, D_weight=1, R_weight=1;
bool printinfo_allot = 1,printinfo = 1;
if(printinfo_allot){
cout<<"Location: "<<"("<<xL<<","<<yL<<")"<<"-------------------------------\n";
cout<<"Same check Letters: "<<x[xL-2]<<","
<<y[yL-2]<<"("<<(x[xL-2] == y[yL-2])<<")"<<"\n";
cout<<"LL: "<<"("<<xL-1<<","<<yL<<")"
<<":"<<arr[yL][xL-1]
<<":"<<(arr[yL][xL-1]+I_weight)
<<":"<<(arr[yL][xL])
<<":"<<(((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1)
<<":"<<(yL>=1 && xL>=1)<<"\n";
cout<<"xL state:"<<((&x[xL]))<<":"<<(x[xL-1])<<"\n";
cout<<"yL state:"<<((&y[yL]))<<":"<<(y[yL-1])<<"\n";
string tx = &x[xL];
cout<<x.length()<<","<<(tx.length()+1)<<"\n";
}
string tx = &x[xL]; // slopy hotfix
if(x.length()==(tx.length()+1)){
cout<<"return functionality not working?-=-=-=-=-=-=-=-=\n";
cout<<"-> Prep last, current distance = "<<arr[yL][xL] <<"\n";
return;
//printOptimalAlignment(arr,y,x,yL-1,xL-1);
//cant use this goto... but where does it go?
//goto because_Im_a_terrible_person;
throw "how?... breaking rules... make it stop";
}
if(yL>=1 && xL>=1 && (x[xL-2] == y[yL-2]) == 1){
if(printinfo){
cout<<"-> Same (same char), current distance = "<<arr[yL][xL] <<"\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL-1);
}
if(yL>=1 && xL>=1 && (arr[yL-1][xL-1] == arr[yL][xL])){
if(printinfo){
cout<<"-> Swap (same int), current distance = "<<arr[yL][xL] <<"\n";
if(arr[yL-1][xL-1]==0)cout<<"---this is last---\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL-1);
}
if(yL>0 && xL>0 && (arr[yL-1][xL]+D_weight == arr[yL][xL])){
if(printinfo){
cout<<"-> Delete, current distance = "<<arr[yL][xL]<<"\n";
}
printOptimalAlignment(arr,y,x,yL-1,xL);
}
//really weird ((yL>1 && xL>1) && (((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1))
//not true if it is?
bool seperate = (((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1);
if(yL>=1 && xL>=1){
if((((arr[yL][xL-1]+I_weight) == arr[yL][xL])==1) && (true)){
if(printinfo){
cout<<"-> Insert, current distance = "<<arr[yL][xL]<<"\n";
cout<<"Next Location1: "<<"("<<xL-1<<","<<yL<<")"<<"\n";
}
printOptimalAlignment(arr,y,x,yL,xL-1);
return;
//how does it get here... also return gets ignored... prob another stack issue
cout<<"insert function broke?????? # (1,1) ???????????????\n";
//return;
}
}
return;
cout<<"END... Hopefully.. if you see this Something went wrong\n";
because_Im_a_terrible_person:
cout<<"QUIT\n";
}
I suspect your problem is that your function calls itself and you don't appear to be taking into account what should happen next after that call to itself finishes. So you get to your finish condition where you say the return doesn't work, but it does... it just returns to where you left off in the previous call to printOptimalAlignment, which still might do something before returning to its caller, and so on. You have three different sites where you recursively call printOptimalAlignment that aren't immediately followed by a return statement, and at any of these it might be that the code will continue and trigger another of your conditional blocks.
include <iostream>
using namespace std;
int Solution(int i_start, int j_start, int i_end, int j_end, int s)
{
int row_dif=i_start-i_end;
int col_dif=j_start-j_end;
while (col_dif !=0 )
{
row_dif=i_start-i_end;
col_dif=j_start-j_end;
if ((row_dif>0) && (col_dif>0))
{
i_start=i_start-2;
j_start--;
}
if ((row_dif>0)) && (col_dif<0)
{
i_start=i_start-2;
j_start++;
}
if ((row_dif<0) && (col_dif>0 ))
{
i_start=i_start+2;
j_start--;
}
if ((row_dif<0) && (col_dif<0))
{
i_start=i_start+2;
j_start++;
}
if (row_dif=0)
{
if (col_dif>0)
{
j_start-2;
}
else if (col_dif<0)
{
j_start+2;
}
else //row_dif=0 dhe col_dif=0
{
cout<<"Problem solved "<<endl;
}
}
}
// col_dif=0
if (row_dif<=-4)
{
i_start=i_start+2;
j_start++;
}
if (row_dif>=4)
{
i_start=i_start-2;
j_start--;
}
}
I am trying to solve Red Knight shortest path with my own method but I am stuck at a part where I need to jump to function start. as an entry-condition I have decided to use row_dif=0 but when row_dif does reach 0 value, I also need to check if there could be more moves (row_dif>=4 or row_dif<=-4) available. And if there are available moves I need to jump to while loop again.
I am stuck at a part where I need to jump to function start
It seems to me like you are stumbling onto the idea of a recursive function. Something along the lines of
return Solution(i_start - 2, j_start - 1, i_end, j_end, s + 1)
Recursion causes the state to be pushed onto the program stack. This idea of a stack is important.
The Red Knight Shortest Path challenge looks to me an awful lot pathfinding. Specifically, A* pathfinding with constrained movements.
The recursive approach uses a stack and is depth-first. For a solution where you want to minimize moves, you want to use a breadth-first approach. You will still wind up using a stack, but your primary structure will be a queue.
As this challenge seems to be geared towards search algorithms, I would suggest studying up on everything I mentioned.
You should write a function int sign( int i ) that returns -1, 0 or +1 for integer less than, equal to or bigger than zero. Then all of your code becomes:
if( row_dif == 0 && col_dif == 0 ) {
// done interrupt
}
i_start -= 2 * sign( row_dif );
j_start -= 1 * sign( col_dif );
plus this code handles situation when col_dif is equal to 0, but row_dif is not, which you did not in your code.
To add your condition change your loop to:
while( true ) {
row_dif=i_start-i_end;
col_dif=j_start-j_end;
if( col_dif == 0 ) {
if( row_dif == 0 ) {
// done
break;
}
if( std::abs( row_dif ) < 4 )
break; // does not look right but follows your logic
col_dif = sign( row_dif );
}
i_start -= 2 * sign( row_dif );
j_start -= 1 * sign( col_dif );
}
Note: comparation operator in C++ is == not = and this is common mistake for novice C++ programmers.
I'm trying to learn more about exception handling while working on my program. I have multiple test variables I want to test and make sure it is within range with:
public bool IsWithinRange(TextBox textbox, string name, int min, int max)
{
double number = double.Parse(textbox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " + min.ToString() + " and " + max.ToString() + ".", "Entry Error");
textbox.Focus();
return false;
}
else { return true; }
}
And calling the method using:
bool condition;
condition = CheckAll();
if (condition == true) { condition = IsWithinRange(txtVar1, "Var1", 1, 50); }
if (condition == true) { condition = IsWithinRange(txtVar2, "Var2", -100, 100); }
if (condition == true) { condition = IsWithinRange(txtVar3, "Var3", 100, 200); }
This logic works, but I was curious to see if there was a more concise, better looking way of writing some form of systematic checking of variables one by one?
You can take advantage of a few things:
Are you able to assign meaningful names to the TextBox.Name properties? If so, you can omit the second parameter in "IsWithinRange" and simply call "Textbox.Name".
As of C# 6.0, there is now a syntax to interpolate strings. So the string passed into your your MessageBox.Show syntax can be made shorter and prettier.
You can immediately assign to "condition", and you can convert your "if" statements to combined "and" statements.
All together, your code can look like this:
bool condition =
CheckAll()
&& IsWithinRange(txtVar1, 1, 50)
&& IsWithinRange(txtVar2, -100, 100)
&& IsWithinRange(txtVar3, 100, 200);
// Some other code here
With your method looking like this:
public bool IsWithinRange(TextBox textbox, int min, int max) {
double number = double.Parse(textbox.Text);
if (number < min || number > max) {
MessageBox.Show($"{textbox.Name} must be between {min} and {max}.", "Entry Error");
textbox.Focus();
return false;
}
else
return true;
}
This is assuming you actually use "condition". If not, you can omit "bool condition = " and the code runs just the same.
But there are a few things to note. Your code will continue to run even if "CheckAll" is false or any "IsWithinRange" is false. This is true in my version above or in your own version. Yes, your user will get a message, but after he clicks "okay", the remaining code will run even if the checks fail.
Also, "IsWithinRange" might be misinterpreted by a teammate or even by yourself in the future. This is because it does more than just return true/false: it sends a message if false. This violates the principle of command-query separation.
An approach to these issues ignores brevity, as that is desired but never the highest goal. What you can do is create a class that validates, whose methods separate the tasks:
class Validator {
public bool isValid = true;
public List<string> messages = new List<string>();
public Validator CheckAll() {
// Whatever your logic is for this.
return this; // Return the instance of "Validator" that called this method
}
public Validator CheckRange (TextBox textbox, int min, int max) {
double number = double.Parse(textbox.Text);
if (number < min || number > max) {
messages.Add($"{textbox.Name} must be between {min} and {max}.");
isValid = false;
}
return this;
}
public void ShowErrorsToUser () =>
MessageBox.Show(string.Join(Environment.NewLine, messages));
}
Which you would use like this:
var validator =
new Validator()
.CheckAll()
.CheckRange(txtVar1, 1, 50)
.CheckRange(txtVar2, -100, 100)
.CheckRange(txtVar3, 100, 200);
if (!validator.isValid) {
validator.ShowErrorsToUser();
txtVar1.Focus();
return; // Stop code execution!
}
// Continue with your normal logic that utilizes your textbox values.
I'll leave it to you to decide whether the class-based approach is worth your time. But I present it to you as a different way to think.
I have a cursor that has its "position" determined by another part of the code. My intention is to have this cursor check through the next and previous object of a vector and check for a condition. If it's valid, the cursor takes this object's position.
Here's some sample code of my idea:
class A
{
bool valid;
public:
A(bool v) {valid=b;}
bool IsValid() {return valid;}
};
void CheckNearbyValidity()
{
/*if the object to the right is valid, update position to this object*/
if(exampleVector.at(cursor-1).IsValid())
{
/*do stuff*/
cursor = (cursor-1);
}
/*if the object to the right isnt valid, try the same thing to the left*/
else if(exampleVector.at(position+1).IsValid())
{
/*do stuff*/
cursor = (cursor+1);
}
/*leave if none are valid*/
}
The problem I encounter here is that if the cursor is at the start or end of the vector, checking the if conditions will cause it to throw an out of range exception.
My solution was to check if the new cursor position was valid before querying the vector:
void CheckNearbyValidity()
{
/*if the object to the right is valid, update position to this object*/
if(cursor-1 >= 0)
{
if(exampleVector.at(cursor).IsValid())
{
/*do stuff*/
cursor = (cursor-1);
}
}
/*new position makes the next condition always true and returns cursor to the same position*/
if(cursor-1 < exampleVector.size())
{
if(exampleVector.at(cursor+1).IsValid())
{
/*do stuff*/
cursor = (cursor+1);
}
}
/*leave if none are valid*/
}
The new problem was that since I could no longe use "else", both conditions would be valid and the cursor would remain where it started.
My workaround to this problem was to surround the function in a while loop, and break when necessary:
void CheckNearbyValidity()
{
while(true)
{
if(cursor-1 >= 0)
{
if(exampleVector.at(cursor-1).IsValid())
{
/*do stuff*/
position = (cursor-1);
break;
}
}
if(cursor-1 >= 0)
{
if(exampleVector.at(cursor+1).IsValid())
{
/*do stuff*/
position = (cursor+1);
break;
}
}
break;
}
}
My question is, is the "single" while loop approach a bad idea? Is there a better way to manipulate this cursor?
You should harness the power of &&:
if (cursor-1 >= 0 &&
exampleVector.at(cursor-1).IsValid())
{
/*do stuff*/
position = (cursor-1);
}
else if (cursor+1 < exampleVector.size() &&
exampleVector.at(cursor+1).IsValid())
{
/*do stuff*/
position = (cursor+1);
}
This allows you to connect the two statements together as an if-else as you had originally, only with the additional validation step checking cursor against the vector bounds.
The && performs short-circuit evaluation. If cursor-1 >= 0 evaluates to false, then the code skips evaluating exampleVector.at(cursor-1).IsValid() and jumps immediately to evaluating the else clause.
Likewise, in the else if clause, if cursor+1 < exampleVector.size() evaluates to false, the && short-circuits and the code skips evaluating exampleVector.at(cursor+1).IsValid(), again making it safe.
Assume I have code like:
if(condition1 || condition2 || condition 3 || condition4)
{
// this inner part will be executed if one of the conditions is true.
// Now I want to know by which condition this part is executed.
}
I'm sure there are better ways to do this, here's one:
int i = 0;
auto check = [&i](bool b)->bool
{
if (!b) ++i;
return b;
};
if (check(false) || // 0
check(false) || // 1
check(true) || // 2
check(false)) // 3
{
std::cout << i; // prints 2
}
|| is short circuit evaluation, so you can have code like this :
if(condition1 || condition2 || condition 3 || condition4)
{
if (condition1 )
{
//it must be condition1 which make the overall result true
}
else if (condition2)
{
//it must be condition2 which make the overall result true
}
else if (condition3)
{
//it must be condition3 which make the overall result true
}
else
{
//it must be condition4 which make the overall result true
}
// this inner part will executed if one of the condition true. Now I want to know by which condition this part is executed.
}
else
{
}
If the conditions are independent of each other, you need to check them separately, or, if they belong to one variable, you can use a switch statement
bool c1;
bool c2
if ( c1 || c2 )
{
// these need to be checked separately
}
int i; // i should be checked for multiple conditions. Here switch is most appropriate
switch (i)
{
case 0: // stuff
break;
case 1: // other stuff
break;
default: // default stuff if none of the conditions above is true
}
Without a switch you can use only or and if statements:
if(condition1 || condition2 || condition 3 || condition4) {
// this inner part will executed if one of the condition true.
//Now I want to know by which condition this part is executed.
if ( condition1 || condition2 ) {
if ( condition1 )
printf("Loop caused by 1");
else
printf("Loop caused by 2");
else
if ( condition3)
printf("Loop caused by 3");
else
printf("Loop caused by 4");
}
I'm not sure that this is the most efficient thing you've ever seen, but it will identify which of the four conditions caused entry into the if ... block.
If you need to know for programmatic reasons, i.e. run different code depending on which condition is true, you could do something like this
if (condition1)
{
...
}
else if (condition2)
{
...
}
else if (condition3)
{
...
}
else if (condition4)
{
...
}
else
{
...
}
If you only want to know for debugging reasons, just do a printout.
What about the comma operator?
By using that logical operators follow the short circuit evaluation method, the following works fine:
int w = 0; /* w <= 0 will mean "no one is true" */
if ( (w++, cond1) || (w++, cond2) || ... || (w++, condN) )
printf("The first condition that was true has number: %d.\n", w);