This is what I want to achieve. In my test fixture I want to call a helper functions with a parameter n to tell the test fixture how many initialization sequences should be expected. Some parameters used in the sequences are stored in three std::vector containers; fileDescriptor, handle, selectionObject.
What I have written is this:
void MyTest::init_Ok(uint32_t n)
{
for (uint32_t i = 0; i < n; ++i)
{
fileDescriptor.push_back(i); // FDs starting at 0
handle.push_back(reinterpret_cast<void*>(18 + i)); // handles starting at 18
selectionObject.push_back(555 + i); // SOs starting at 555
EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
.WillOnce(DoAll(SetArgPointee<0>(handle[i]),
Return(INIT_OK)));
EXPECT_CALL(MyMockApi::getApi(), selectionObjectGet(handle[i], Pointee(nullptr)))
.WillOnce(DoAll(SetArgPointee<1>(selectionObject[i]),
Return(SELECTION_OK)));
EXPECT_CALL(MyMockApi::getApi(), finalize(handle[i]))
.WillOnce(Return(FINAL_OK));
}
}
I know why it's not working. It is expected that all calls to initialize will be identical but yet I want to perform different actions (parameter depending on loop counter i) for the first, second, third, ..., nth call. The current implementation will only expect one call to initialize no matter parameter n. Is it possible to fix this and keep it a loop somehow, or do I have to add the actions with a WillOnce line for each i? This would mean i have to check n and add different number of WillOnce lines for different possible values of n, which i really want to avoid.
One way could be to use Invoke. You can write a function which will have access to the handles container and a running member/static variable(lets say counterVar) which will indicate the number of times the function is hit. Based on the value of counterVar, you can decide the logic.
.WillRepeatedly(Invoke(<your function>))
Something like:
EXPECT_CALL(MyMockApi::getApi(), initialize(Pointee(nullptr), StrEq("InitString"), MyMatcher()))
.WillRepeatedly(Invoke(successfulInitialize));
ReturnCode successfulInitialize(void* op, std::string msg)
{
static int counterVar = 0;
*op = handles[counterVar++];
return INIT_OK;
}
Related
I am facing following problem with recursion. It is simple backtracking to print all the permutation, but I want to stop it from the base condition. For example, 4 character string will show 4!=24 strings. But I want to show first 20 strings only.
k is used for the purpose, k=20,for the example. Suppose, str="ABCD". I want to stop recursion after exactly 20 operations. How can I do this? I have tried to solve it in this way.
void permutation(string str,int l,int r,int k)
{
k--;
if(l==r||k==0) {
cout<<str<<endl;
return;
}
else{
for(int i=l;i<r;i++)
{
swap(str[l],str[i]);
permutation(str,l+1,r,k);
swap(str[l],str[i]);
}
}
}
If you want to use the unfortunately named k as a counter like that, it will count recursion levels, not results. If you want to count results, you need to store the counter outside of your function, either as a static or as a reference you pass to your function, and increment it every time you output a result.
You have two solutions to count the number of times results are printed:
1- Defining k as a global variable outside the function.
2- Defining k as a static variable: static int k = 0;.
Note that in both these solutions, k should be eliminated from the parameter list of the function.
I would also suggest choosing meaningful names for your variables. This way, it will be easier to understand and follow the code both for you and someone else who is going to help.
I want to have a function to make a list of binary random numbers.. I don't know which method is appropriate for this purpose. I can make it with an array , a while command, linked list or a std ..
I want to return the whole list from the function. In array i think i can't do that. For example the following function only return the first elements.
long int SourceNode::database(long int chunk_var[])
{
srand ( time(0) );
for(int j = 0; j<50 ;j++)
{
int myrand = rand() % 2 ;
myrand = myrand & 0x3ff;
chunk_var[j]= myrand;
}
return *chunk_var;
}
i want something to return the whole list, because i want to invoke that function( the whole list) in another function . is there any alternative solution instead of making an array?
You can return a vector<bool> or a vector<uint32_t>. That will be easier than any other option. BTW, C++11 added a new random number generator that is friendlier and probably uses a better underlying algorithm than rand.
Just return the array you got as a parameter:
long int *SourceNode::database(long int chunk_var[])
{
......... // fill the array with numbers
return chunk_var;
}
However I suppose you will also need to pass the array length to the function as another parameter so that the function knows how many items it is allowed to overwrite.
I'm working on threads, however before I use threads I am to write 2 programs.
Set up an array and write a sequential program that accesses the whole of the array and performs some simple task on the contents.
Modify the program so that it is still sequential but accesses the array by a series of calls to a function. Each call to that function will process a number of rows of the array as defined by a parameter passed to the function.
I'm having problems understanding the questions, it seems so simple but yet I can't seem to get my head around it. I am to write the programs based on the above two questions before I start creating a program that will allow the processing to be carried out in one or more threads. Each thread should access a different set of rows of the array.
For the first question, the code I have written so far is
#include <iostream>
#include <stdio.h>
int main()
{
int array [20][20];
int i, j;
/* output each array element's value */
for ( i = 0; i < 20; i++ )
{
for ( j = 0; j < 20; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j] );
}
}
system ("PAUSE");
return 0;
}
I want to know if the above program is a sequential program? I have run the program and it access the whole array and perform one tasks which is to print out all data in the arrays.
I researched on on-line what it means by sequential program and I found it means the following statement: perform task a before task b but not at the same time. Is this right?
For the second part I have done the following:
#include <iostream>
#include <stdio.h>
void print_array(int array[20][20]);
int main()
{
int array [20][20];
int i, j;
print_array(array);
system ("PAUSE");
return 0;
}
// Output data in an array
void print_array(int array)
{
int i, j;
for ( i = 0; i < 20; i++ )
{
for ( j = 0; j < 20; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j] );
}
}
}
Am I going in the right direction? As I also got to write a version of the program that will allow the processing to be carried out in one or more threads.
EDIT: I am to use 2D arrays, sorry it wasn't clear above
I don't think you're going in the right direction, but you're not far off. What the instructions are asking for are some of the preliminary steps needed to take the work of processing an array sequentially and make it run in parallel. When writing a parallel program, it is often useful to start with a working sequential program and slowly transform it into a parallel program. Following the instructions is a way to do this.
Let's consider the parts of the question separately:
Set up an array and write a sequential program that accesses the whole of the array and performs some simple task on the contents.
The simple task that you chose for your array is to print the contents, but this isn't a suitable task, because it has no functional result. A more suitable task would be the sum the elements in the array. Other tasks might be count the elements that meet some condition, or to multiple each element by two.
So, first try to modify your initial program to sum the elements instead of printing them.
(In your code you are using a two-dimensional array. I would suggest using a 1-dimensional array for simplicity.)
Modify the program so that it is still sequential but accesses the array by a series of calls to a function. Each call to that function will process a number of rows of the array as defined by a parameter passed to the function.
In this part what you are trying to do is break up the functionality into small pieces of work. (Eventually you will send these units of work to threads for processing, but you are just doing the preliminary steps now.) If we did a sum in part 1, then here you might write a function which is int sumKitems(int *array, int startIndex, int numItems). The main program would then call this on each set of (say) 10 items in the array, and combine the full results by summing the results from each sumKitems call.
So, if there are 100 items in the array, you could make 10 calls to sumKitems(...), telling the function to process 0...9, 10...19, ..., 90...99. This would be in place of doing the sum on all 100 items individually.
--
To summarize, part one would be a simple for loop, not too differently from what you've written, just with some computation being performed.
The second part should do exactly the same computation and return exactly the same result, just using another function call which handles k items at time. (If you pass the number of items to handle at a time as a parameter you will be able to balance the cost of communication vs work being done when moving to a threaded implementation.)
In the end, you will probably be asked to replace the call to sumKitems(...) with a queue that sends work to the threads to do independently.
I believe that if you are not creating separate threads in any way then you are in fact writing a sequential program. There is no part of your code where you jump into a new thread to do some operation while the main thread does something else.
Summary: your code runs on a single thread - it is sequential
You must pass the array not as an integer but as a double pointer -> int array[][] or int** array
To perform operations on the array sequentially would be to start at the first place in the array and increment through the array performing operations as you go
array[10] = {0,1,2,3,4,5,6,7,8,9}
iterate through array with some action such as adding +5
array [10] = {5,6....}
To make this multi-threaded you need to have different threads operate on different segments of the array such as places 0-4,5-9 and perform the action so it can be done in less time. If you're doing it this way you will not need to worry about mutexes.
So Thread one increments through array[10] {0,1,2,3}
Thread two increments through array[10] {4,5,6,7}
Each increment one place at a time and both threads run concurrently
I'm writing a function for calculating integrals recursively, using the trapezoid rule. For some f(x) on the interval (a,b), the method is to calculate the area of the big trapezoid with side (b-a) and then compare it with the sum of small trapezoids formed after dividing the interval into n parts. If the difference is larger than some given error, the function is called again for each small trapezoid and the results summed. If the difference is smaller, it returns the arithmetic mean of the two values.
The function takes two parameters, a function pointer to the function which is to be integrated and a constant reference to an auxiliary structure, which contains information such as the interval (a,b), the amount of partitions, etc:
struct Config{
double min,max;
int partitions;
double precision;
};
The problem arises when I want to change the amount of partitions with each iteration, for the moment let's say just increment by one. I see no way of doing this without resorting to calling the current depth of the recurrence:
integrate(const Config &conf, funptr f){
double a=conf.min,b=conf.max;
int n=conf.partitions;
//calculating the trapezoid areas here
if(std::abs(bigTrapezoid-sumOfSmallTrapezoids) > conf.precision){
double s=0.;
Config configs = new Config[n];
int newpartitions = n+(calls);
for(int i=0; i < n;++i){
configs[i]={ a+i*(b-a)/n , a+(i+1)*(b-a)/n , newpartitions};
s+=integrate(configs[i],f);
}
delete [] configs;
return s; }
else{
return 0.5*(bigTrapezoid+sumOfSmallTrapezoids);}
}
The part I'm missing here is of course a way to find (calls). I have tried doing something similar to this answer, but it does not work, in fact it freezes the pc until makefile kills the process. But perhaps I'm doing it wrong. I do not want to add an extra parameter to the function or an additional variable to the structure. How should I proceed?
You cannot "find" calls, but you can definitely pass it yourself, like this:
integrate(const Config &conf, funptr f, int calls=0) {
...
s+=integrate(configs[i],f, calls+1);
...
}
It seems to me that 'int newpartitions = n + 1;' would be enough, no? At every recursion level, the number of partitions increases by one. Say conf.partitions starts off at 1. If the routine needs to recurse down a new level, newpartitions is 2, and you will build 2 new Config instances each with '2' as the value for partitions. Recursing down another level, newpartitions is 3, and you build 3 Configs, each with '3' as 'partitions', and so on.
The trick here is to make sure your code is robust enough to avoid infinite recursion.
By the way, it seems inefficient to me to use dynamic allocation for Config instances that have to be destroyed after the loop. Why not build a single Config instance on the stack inside the loop? Your code should run much faster that way.
Sorry to bother again, but as I am new C++ I am having a lot of weird and silly problems.
I am programing a MCMC method. I read in this forum that the WELL RNG was a good alternative to generate random numbers so I am trying to make it work. So here the questions:
I am compiling the "Well44497a.c" within my c++ project without further modifications. It compiled. Is that right or should I make any change?
I am using the following scheme inside my code but it is just generating a cycle of 3 RN
SOLVED: The problem was that InitWELLRNG44497a(state) should be placed outside the function. I was re initiating the generator every time I was generating a sample. For the whole run the generator has to be initialized just once.
int* sampler(PARAMETERS) { //this function returns a sample
int k;
unsigned int state[1391];
for (k = 0; k < 1391; ++k)
{
state[k] = k;
}
InitWELLRNG44497a(state); //THIS SHOULD GO ON THE CALLER FUNCTION NOT HERE
double value_first = valuate(first_state); // this function valuates one of two possible states
double value_second = valuate(second_state);
double rand_number = WELLRNG44497a()
if(rand_number > value_first / (value_first + value_second))
return second_state;
else
return first_state;
}
Your function appears to initialise the state array with the same values every time you call your sampler() function. The idea of the state array is that it holds the current state of the random number generator, and that you don't fiddle with the contents of state between calls to the RNG.
Make the state array global in your program, initialise it once, and don't touch it after initialisation.