Problem with random numbers

Hey guys , as from what i read up , the function srand() and rand() are able to give u random numbers if they are being run one time only. What i am trying to do is to produce a set of random and unique numbers from 1 - 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using namespace std;
int main ()
{

    int num[10];
    

srand((unsigned)time(0));

int random_integer;

for(int index=0; index<10; index++){

random_integer = rand()%10;
for(int i = 0;i< index ; i++)
{
    if(num[i] == random_integer){
        random_integer = rand()%10;
        num[i] = random_integer ;
    }
    else{
    cout << "non" << endl;
    }
}
        cout << random_integer << endl;

}
   
    

}



What i try to do is to generate the random number, store it inside a array. Then within that for loop , i would do a check to see if the number already exist . if it does, another random number will be generated.

The problem i am facing is that, the number does not seem to replace itself. I tried various ways of playing around with the loop but to no avail. Hope for some help. Ty.
You may want to use a while loop, perhaps something like this (pseudocode):

while (number_is_taken){
random_integer = random_number;
check if random_integer is taken
}
You can choose a algorithm that cost time is less.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void Shuffle()
{
	for(int count = 0; count < 10; count++)
	{
		int carPos1 = rand()%allNumberNumMax;
		int carPos2 = rand()%allNumberNumMax;
		IterNumber(carPos1, carPos2);
	}
}


void IterNumber(int carPos1, int carPos2)
{
	int tmp = m_nowNumber[carPos1];
	m_nowNumber[carPos1] = m_nowNumber[carPos2];
	m_nowNumber[carPos2] = tmp;
}
Well I like simo110's solution much better! As a matter of fact, i'm utilizing that in a few of my programs. Good suggestion!
Actually, you should use random_shuffle, because that's exactly what it does.

http://www.cplusplus.com/reference/algorithm/random_shuffle/
Topic archived. No new replies allowed.