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.
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 am trying to create a circular reference to array. For example,
float arr1[10] = {0,1,2,3,4,5,6,7,8,9};
Then I use a variable in loop to access elements of array.
for (int i=0;i<10;i++){
std::cout<<arr1[i]<<std::endl;
//other processing using arr1[i] indexing
}
Here, I can only use i<=10. If I want to make i<=16 and if i>10 then index should go to arr1[0] and proceed from there. What are preferable or recommended ways to do this?
You need to use the modulo operator %.
14 % 10 = 4 So just do this with the index you use to access it.
You should use like #Jdman1699 said the modulo operator. Here you find an example:
int position; //the position you want to get
float out = arr1[position%10];
For your specific program, I would simply suggest putting your base for loop inside of another for loop (as it seems that you want to print out all elements of the array many times over, considering your source code). This is because accessing element n is no different than accessing element n + 10. However, if you are planning to create some sort of function to access any element of the array, I would use the modulo operator-base 10. Maybe,
unsigned long int newidx = iptidx%10;
and then work with newidx.
May be u r looking for...
for (int i=0;i<10;i++){
std::cout<<arr1[i%10]<<std::endl;
//other processing using arr1[i] indexing
}
I seen weird for loop syntax in C++. Please see following program.
#include <iostream>
using namespace std;
int main()
{
int num, count = 0;
int array[]= {1,1,2,3,4,1,3,2,9,8,7};
cout<<"Which number would you like to know about how many times it appeared?"<<endl;
cin>>num;
for (int i:array)
{
if (i == num)
++count;
}
cout<<"Number "<<num<<" appeared "<<count<<" times in the array"<<endl;
return 0;
}
It is successfully run on GCC Linux platform.
Reference link Here.
So, My question is, Is it the correct way to use for loop in C++?
Also, Is for (int i:array) equivalent to for ( int i:array ; ; )?
Sorry for my poor english. Thanks in advance.
There are now (since C++11) two distinct syntaxes for for-loops, the old C-style:
for (initialization; test; increment)
and the new
for (declaration: container)
In the new syntax, the declaration declares a variable which is successively given the value of each element of the container. Common values of "declaration" are auto val, const auto val, auto& val, and const auto& val, depending on whether you want a reference to the value in the container or a copy, and whether you want the value constant or not.
Both syntaxes are correct. It rather depends what you want to do in the loop. My preference is to use the range based for unless I am going to need the loop counter or iterator ... in which case I fall back on the old style for.
See http://en.cppreference.com/w/cpp/language/range-for for the gory details of the specification (and what is meant by "container").
The syntax for (int i:array) iterates through each element in the array, compared to for (int i = 0; i<sizeof(array); i++) which creates a counter that automatically increments on each iteration of the loop. The counter can then be used to access elements of the array with array[i]
As for which one you'd use, it depends on what you want to do. In your example there isn't a need to keep track of which iteration of the loop you are on, so the former will work fine. If you wanted to, say, print the iteration number each time then you would use the latter.
P.S. your English is perfect :)
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;
}
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.