Increment variable on every call of method - c++

I have this method :
void Session::onNewImage(cv::Mat& img, double elapsedTime){
static int count = 0;
add(img, dnnOutput[count++], curLati, curLongi, curAlti, curHeading, curRoll);
}
It's been called 1400 times. Each time the value of "count" is incremented. But when it comes at 1401 time, I want "count" to become 0 , and then again increment form there. I don't want "count" to be a global variable. How can i achieve this ?
P.S. I cannot hard code it as 1400. It can be different everytime. There is another method which decides how many times this method will be called, Depending on number of images given as input to that method.

This should do it:
void Session::onNewImage(cv::Mat& img, double elapsedTime){
static int count = 0;
if (count >= getYourCountLimitFromSomewhere())
count = 0;
add(img, dnnOutput[count++], curLati, curLongi, curAlti, curHeading, curRoll);
}
Note that as #Aconcagua has pointed out in the comments, whether the comparison of count with the threshold is via > or >= depends on the meaning of the getYourCountLimitFromSomewhere() return value.

Related

Initializing An Array with a Variable Size

I am almost done with my code except I need help on two thing. Here is my code: Code. For the function below, I am trying to make it so that I can use the input of "n" to initialize my array, myBits, instead of a constant, which is currently 5.
My Other question is right below that. I am trying to switch all of the right most bits to "true". I wrote the for loop in "/* .....*/" but it doesn't seem to be working. Right above it, I do it long ways for C(5,4) ....(myBit[0] = myBit[1]....etc...... (I am using this to find r-combinations of strings).... and it seems to work. Any help would be appreciated!!
void nCombination(const vector<string> &Vect, int n, int r){
bool myBits[5] = { false }; // everything is false now
myBits[1] = myBits[2] = myBits[3] = myBits[4] = true;
/* for(int b = n - r - 1; b = n - 1; b++){
myBits[b] = true; // I am trying to set the r rightmost bits to true
}
*/
do // start combination generator
{
printVector(Vect, myBits, n);
} while (next_permutation(myBits, myBits + n)); // change the bit pattern
}
These are called variable length arrays (or VLAs for short) and they are not a feature of standard C++. This is because we already have arrays that can change their length how ever they want: std::vector. Use that instead of an array and it will work.
Use std::vector<bool>:
std::vector<bool> myBits(n, false);
Then you have to change your while statement:
while (next_permutation(myBits.begin(), myBits.end()));
You will also have to change your printVector function to take a vector<bool>& as the second argument (you won't need the last argument, n, since a vector knows its own size by utilizing the vector::size() function).
As to your program: If you're attempting to get the combination of n things taken r at a time, you will need to write a loop that initializes the last right r bools to true instead of hard-coding the rightmost 4 entries.
int count = 1;
for (size_t i = n-1; i >= 0 && count <= r; --i, ++count)
myBits[i] = true;
Also, you should return immediately from the function if r is 0.

Is there a way to make a function do something different the second time a number appears?

Im trying to make a small program about the method in which the amount of money awarded to players at the end of a game is decided. So far I have used a RNG to simulate what happens in a round of the game but have gotten stuck. I want to find out how to design my code in order for it to do something different the second time the same number is generated from the RNG.
while (active==1)
{
random=rand()%11+1;
if (random==11)
{
bomb=1;
}
}
Thanks for any responses :)
Keep a map of (number, count) pairs:
std::unordered_map<int, std::size_t> number_frequencies;
while (active) {
int number = random_number();
++number_frequencies[number];
if (number_frequencies[number] == 2) {
// do something
} else {
// do something else
}
}
First of all, for clarity, apply the following:
Define MAX to whatever maximum value you want to have (e.g., 11)
Use random between 0 and MAX-1 (instead of between 1 and MAX)
Then, you can try to adjust the following piece of code to your requirements:
#define MAX 11
...
int count[MAX] = {0};
while (active == 1)
{
random = rand()%MAX;
count[random]++;
...
}
The count array indicates the number of times that each random value was generated.
So at each iteration, you can use count[random] in order to choose what action to take.

knights tour in c++ using recursion

I have created a class Board which deals with 2d vectors specifically for this purpose. I am trying to solve the Knight's Tour. I want to print out the thing when it is done. Using the recursive voyagingKnight() function I find that it does not do anything, does not print the result. It seems that I would want to increment the step number for the recursive call but this is not working.
The vector argument incs is a 2d vector of increments for moving the knight, in each row a row move in the first colum and a column move in the second column.
Does anyone have any suggestions as to a flaw in my reasoning here?
The relevant code
bool voyaging_knight( Board &board, int i, int j, int steps ,vector< vector<int> > &increments)
{
if( !newplace(theboard, i, j) ) return false;
board.setval(i,j,step);
if( gone_everywhere( board, steps) )
{
cout <<"DONE" << endl;
board.showgrid();
return true;
}
int n;
int in, jn;
for(n=0; n<8; n++ )
{
in = i + increments[n][0];
jn = j + increments[n][1];
if( inboard(board, i, j)&& newplace(board,i,j) )
{
voyaging_knight( board, in, jn, steps+1 ,increments);
return true;
}
}
theboard.setval(i,j,-1);
}
Yes, change this:
voyagingKnight( theboard, inext, jnext, step+1 ,incs);
return true;
To this:
return voyagingKnight( theboard, inext, jnext, step+1 ,incs);
In addition, it seems that you need to return something (probably false) at the end of the function.
BTW, I'm assuming that you have all the entries in theboard initialized to -1.
I'm guessing that you want 1 continuous path made by horse movements on a (chess)-board found by backtracking. In that case you have to pass the board by value, so each path you take has its own instance to fill. By passing by reference, every path fills the same board, so you can never take all the steps.
Also you should pass a result by value and fill it with the positions you visited and return that from the recursive function, so each path has its own instance of resulting positions and by returning it, you end up with the final result.
You should not pass inc because that is just a helper container that doesn't change.
Make the board a global variable, and build up a sequence of visited squares in a global variable too. Make sure that when retracting each tentative step you undo any changes (square visited, last step of sequence). Call your knight's tour function, make it return success if it reaches the end, and do any output after finishing.
Package the whole shebang in a file or as a class, so as to not expose private details to prying eyes.

Count the number of matching elements in two arrays C++

I'm working on a homework assignment for Comp Sci I, and I've tried literally everything I could find on the internet and in my textbook in an attempt to count the number of matching elements in two C++ arrays. I simply can't find a way to make my code count the number of matching elements in two arrays of the same size (same value, same position). For instance, if array1 has 5, 4, 3, 2, 1, and array2 has 1, 2, 3, 4, 5, there is one matching element, the 3. How can I get my code to perform this seemingly simple task?
Couldn't find an answer anywhere. My textbook only shows how to see if the arrays match exactly without counting the number of matches, and I haven't been able to find anyone else with this exact question for C++.
Here's my function so far:
int matchCounter(int lottery[5], int user[5], int matches, int SIZE)
{
int count = 0;
for (count < SIZE; count++;)
{
if (lottery[count] == user[count])
{
matches++;
}
}
return matches;
} // end matchCounter
SIZE is a constant that equals 5, by the way. It would seem that this should work, but every time I run the program, it displays 0 matches, even in there are some matches. If anyone could help me out, I would be forever in your debt. Seriously, there's got to be some incredibly simple thing I'm just not seeing. Thanks for you help in advance.
Your for statement is garbled. Try this:
int matchCounter(int lottery[5], int user[5], int matches, int SIZE)
{
for (int count = 0; count < SIZE; count++)
{
...
For reason why your program always fails: count++ is put in the position of the condition in the for loop, so every time this for loop is executed, count is evaluated and considered to be the condition, and then count is incremented by 1. However, every time count starts from 0 (as in int count = 0;), so the for loop actually never gets executed, and matches remain zero.
EDIT:
From your source code, you're not using your return value, which is also suggested by #jimhark. Change the function signature to:
int matchCounter(int lottery[5], int user[5], int SIZE)
And call with:
matches = matchCounter(lottery, user, 5);
Otherwise, your return value of the function matchCounter is ignored, while int matches only plays the role of a local variable in the function.
Read this about why the matches doesn't work: http://www.cs.utsa.edu/~wagner/CS2213/swap/swap.html (in a similar setting)
Since this is a homework, I will try to point the errors without giving the solution.
The form of a for loop is:
for (INIT; COND; STEP) {
BODY;
}
which is equivalent to:
INIT;
while (COND) {
BODY;
STEP;
}
The way you did, your INIT is count < SIZE, which doesn't do anything. Your "COND" is count++, which returns 0 on the first iteration. As you may know, 0 is false, in the context of a boolean. Therefore, your for loop body is not being executed at all.
Also, you should not pass matches as an argument. It should be a local variable initialized with 0.
Your may not be using your return value. Change sig to:
int matchCounter(int lottery[5], int user[5], int SIZE)
{
matches = 0;
And make sure your're calling with:
matches = matchCounter(lottery, user, 5);
If you need a running sum, use:
matches += matchCounter(lottery, user, 5);
In any case matchCounter doesn't care what running total is, so why pass it in?
Also you may need to sort the lists first.
Maybe this can help:
int matches=0;
for(int i=0;i<ARRAY.SIZE;i++) {
for(int j=0;j<ARRAY.SIZE;j++) {
if(arr1[i]==arr2[j]) {
matches++;
arr2[j]=NULL;
}
}
}

Vector push_back in while and for loops returns SIGABRT signal (signal 6) (C++)

I'm making a C++ game which requires me to initialize 36 numbers into a vector. You can't initialize a vector with an initializer list, so I've created a while loop to initialize it faster. I want to make it push back 4 of each number from 2 to 10, so I'm using an int named fourth to check if the number of the loop is a multiple of 4. If it is, it changes the number pushed back to the next number up. When I run it, though, I get SIGABRT. It must be a problem with fourth, though, because when I took it out, it didn't give the signal.
Here's the program:
for (int i; i < 36;) {
int fourth = 0;
fourth++;
fourth%=4;
vec.push_back(i);
if (fourth == 0) {
i++;
}
}
Please help!
You do not initialize i. Use for (int i = 0; i<36;). Also, a new variable forth is allocated on each iteration of the loop body. Thus the test fourth==0 will always yield false.
I want to make it push back 4 of each number from 2 to 10
I would use the most straight forward approach:
for (int value = 2; value <= 10; ++value)
{
for (int count = 0; count < 4; ++count)
{
vec.push_back(value);
}
}
The only optimization I would do is making sure that the capacity of the vector is sufficient before entering the loop. I would leave other optimizations to the compiler. My guess is, what you gain by omitting the inner loop, you lose by frequent modulo division.
You did not initialize i, and you are resetting fourth in every iteration. Also, with your for loop condition, I do not think it will do what you want.
I think this should work:
int fourth = 0;
for (int i = 2; i<=10;) {
fourth++;
fourth%=4;
vec.push_back(i);
if (fourth==0) {
i++;
}
}
I've been able to create a static array declaration and pass that array into the vector at initialization without issue. Pretty clean too:
const int initialValues[36] = {0,1,2...,35};
std::vector foo(initialValues);
Works with constants, but haven't tried it with non const arrays.