Solved [Solved] ten different random integers

MNIHKLOM

Member

Reaction score: 4
Messages: 64

Hi sirs,

I want to get ten(10) different random integers with rand(3) but almost all the time fail to get ten different numbers. My code is as follows:

Code:
int  left[9]={0,0,0,0,0,0,0,0,0}, k;
for (k=0;k<9;k++)
left[k]=rand() % 10;

for (k=0;k<9;k++)
printf("integer[%d] is %d\n",k,left[k]);
Would anyone here point out the better codes please.

With best regards,
MNIHKLOM
 

kpa

Beastie's Twin

Reaction score: 1,801
Messages: 6,318

10 different random numbers when your target domain is only 10 numbers? The probability of that happening with your solution is very very small ;) I think what you want instead is a random permutation of numbers (0..9). The C library does not have such a function as far as I know but you can probably find a suitable algorithm yourself by googling.
 

funky

Member

Reaction score: 12
Messages: 41

Hi,

a simple variant would be:

Code:
int permutation[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for ( int k = 0; k < 10; k++ ) {
  int r = rand() % 10;
  int tmp = permutation[k];
  permutation[k] = permutation[r];
  permutation[r] = tmp;
}
 

j_m

New Member

Reaction score: 2
Messages: 10

Because 10 numbers is in container [0~9], two or more random numbers are the same number is normal. So maybe you just want to randomly sort them?

Maybe you can pass it by checked.
 
OP
OP
MNIHKLOM

MNIHKLOM

Member

Reaction score: 4
Messages: 64

Hi,

Thanks to every answers and thank you indeed for your times. My purpose of generating this array of integers is to give a plus table of integers to my children as an exercises. If I wrote down directly from 1+1 2+1 3+1 ... 9+1 to 9+9, some clever kids will not do that kind of home work.

My problem now is that the codes generate the same as for every run. I should try srand(3) in a short time.

Once again many thanks indeed for your times and apologized me for my English.

With best regards,
MNIHKLOM
 

overmind

Well-Known Member

Reaction score: 32
Messages: 332

At the beginning of your main() function, call:

Code:
srand((unsigned int)time(0));
You will need to include:

Code:
#include <ctime>
Call srand() function just once.
 
OP
OP
MNIHKLOM

MNIHKLOM

Member

Reaction score: 4
Messages: 64

overmind said:
At the beginning of your main() function, call:

Code:
srand((unsigned int)time(0));
You will need to include:

Code:
#include <ctime>
Call srand() function just once.
Hi,

This gives good results. But I only include time.h as suggest by time(3).
Many thanks indeed for your valuable hints.

With best regards,
MNIHKLOM
 
Top