How can I fill in an array with random numbers?

I want to fill an array with random numbers 1-32, but each one should be in there only once. This code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for(counter=0;counter<32;counter++)
{
	do
	{
		randnum = rand() % 32 + 1;
		i = SequentialSearch(randnumvect, randnum);
		if(i!=-1)
			returned==randnum;
		else
			returned==-999;
	}
	while(randnum==returned);
	randnumvect.resize(randnumvect.size()+1);
	randnumvect[counter] = randnum;
}


With this sequential search:

1
2
3
4
5
6
7
8
9
10
11
12
int SequentialSearch(const vector<int> &randnumvect, int search)
{
	int i;
	
	for(i=0;i<randnumvect.size();i++)
	{
		if(search==randnumvect[i])
			return i;
	}
	i = -1;
	return i;
}


Puts the numbers in randomly, but there are some repeats. What am I doing wrong?
Last edited on
1
2
3
4
5
6
#include <algorithm>

for ( counter=0; counter <32; ++counter )
    randnumvect.push_back(counter+1) ;

std::random_shuffle( randnumvect.begin(), randnumvect.end() ) ;
Last edited on
Thanks! It works! Is there any way to modify the code I posted?
closed account (4z0M4iN6)
Gregory Sakas wrote:

Thanks! It works! Is there any way to modify the code I posted?

You could edit your post
Do not be hurry. Your code is invalid. You use the comparision operator instead of the assignment operator in the following code snip

if(i!=-1)
returned==randnum;
else
returned==-999;
Topic archived. No new replies allowed.