• C

# array of random integers

How can I create a function to fill an array with random integers between 1 and 100?
###### Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

DBACommented:

Use the random() function.

The function returns a value from 0 to (the limit that you pass - 1).  Since you want 1 to 100, you should call random(100) and add 1 to the value before you store it into the array location.

Array[position] = random (100) + 1;

Since this is probably homework, you'll have to build all of the other controls yourself.

Good Luck,
Kent
0
Commented:
try:

randomize();
for(i=0;i<1000;i++) { //suppose that the array have size 1000
array[i] = rand()%100+1; //0-99 + 1, so it's 1 to 100

Hope this help.
thanks

0
Commented:
If your library doesn't have random() or randomize() or you otherwise want to confine yourself to standard C library functions, use rand() to generate a random integer and srand() to initialize the pseudo-random number generator.

http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand

--efn
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
Hi kent,

random function does not take any argument. It simply generates random numbers between 0 and 2^31 - 1.

Alrtel,

Use this....

#define RAND_MAX 99

Array[position] = rand() + 1;

(RAND_MAX is defined in stdlib.h)

JunkJunkJunk
0
DBACommented:

Hi junkjunkjunk,

You're partially correct.   The win32 implementation of random() accepts an integer argument that is the upper limit + 1.  (You want a range of 100 numbers, you pass 100 and the returned value will be from 0 to 99.)

rand() is more general and should be available on all platforms.

Kent
0
Commented:
/* I used this snippet to generate sequence of 109 for a teddy bear name raffle.
Array is used to avoid repeats.
Output is the random sequence */

#include <stdlib.h>

int main( void ) {

int i, count = 0;
int array[110];

for ( i = 0; i < 109; i++ ) array[i]=0;
srand( time( NULL ) );
while ( count < 109 ) {
i = 1 + (int) (109.0*rand()/(RAND_MAX+1.0));
if ( i != array[i] ) {
array[i] = i;
printf( "%d == %d\n", ++count, i );
}
}
exit(0);
}
0
DBACommented:

Hi earthman2,

If you wan't to create a "list" of integers so that you don't get repeats there's a more efficient way.  It does kind of skew the statistical "norm", but when I'm electronically dealing cards, I certainly want 52 DIFFERENT cards!  :)

#include <stdlib.h>

#define LIMIT 100

int Array[LIMIT];

main ()
{
int idx, other_idx, save;

for (idx = 0; idx < LIMIT; idx++)   /*  Initialize every element of the array it its position  (index value)  */
Array[idx] = idx;

for (idx = 0; idx < LIMIT; idx++)  /*   Randomly swap element pairs.  Every element will be swapped at least once  */
{
other_idx = rand() % LIMIT;
save = Array[idx];
Array[idx] = Array[other_idx];
Array[other_idx] = save;
}
}

Hmmm.... Looking back, our "solutions" might have been what the original poster was looking for.   :)

Kent
0
Commented:
Hello,
I was reading all that you wrote here, and my problem seems similar to me.

i am writing a method which will fill the array of size 7 with random numbers from 1 to 30, but the numbers cannot be zero and cannot repeat within the array.
i have tried so many ways and nothing works.

G.
0
Commented:
This is my code, maybe someone can find a mistake there (it allows duplicate values in array)

int []GetLotteryNumbers()
{

int[]lotteryNums=new int[7];

bool isDup = false;

for (int i=0;i<=6;i++)
{
int randomNumber=RandomInt(31);

if (randomNumber!=0)
{
lotteryNums[i]=randomNumber;

foreach (int num in lotteryNums)
{
if (num == randomNumber)
{
isDup = true;
break;

}
if (!isDup)
{
lotteryNums[i]=randomNumber;
}
}

}

}
return lotteryNums;
}
0
Commented:
for (idx = 0; idx < LIMIT; idx++)  /*   Randomly swap element pairs.  Every element will be swapped at least once  */
{
other_idx = rand() % LIMIT;
save = Array[idx];
Array[idx] = Array[other_idx];
Array[other_idx] = save;
}
}
This produces a biased distribution
other_idx =  rand() % (idx+1);
0
DBACommented:
Hi ozo,

As long as rand() is evenly distributed, the original "swap pairs" logic is sound.  Every element is assured of being the "source" in a swap at least once, and will statistically be the "destination" once.  The number of times each element is the destination can vary -- randomness allows each element to be the destination any number of times, including zero.

The suggestion to use (idx+1) instead of (LIMIT) doesn't improve the distribution.

#define LIMIT = 100
#define ITERATIONS = 10000

long Count[LIMIT] = {0};
int   Array[LIMIT];

for (iter = 0; iter < ITERATIONS; iter++)
{
for (idx = 0; idx < LIMIT; idx++)  /*  Initialize the array to 1,2,3,4...LIMIT */
Array[idx] = idx;

for (idx = 0; idx < LIMIT; idx++)  /*   Randomly swap element pairs.  Every element will be swapped at least once  */
{
other_idx = rand() % LIMIT;
save = Array[idx];
Array[idx] = Array[other_idx];
Array[other_idx] = save;
}
for (idx = 0; idx < LIMIT; idx++)  /*  Count the value by position  */
Count[idx] += (long)Array[idx];
}

for (idx = 0; idx < LIMIT; idx++)   /*  Display the distribution  */
printf (" %3d  %8.4f\n", (float)Array[idx]/(float)LIMIT);

Kent
0
Commented:
consider LIMIT = 3
rand % LIMIT 3 times gives 27 equally likely posibilities
But there are 6 possible permutations of 3 elements
therefore some of the 6 premutations will be generated more often than others
0
DBACommented:

Hi ozo,

After thinking about this for a few minutes, I came to the conclusion that number of swaps shouldn't matter -- as long as the chances of any one swap occuring is equal to the chance of any other swap.

Then I set about proving it, and was surprised to see that you are in fact, correct.  The distribution of occurences skews so that 3 outcomes occur 4/27ths of the time and the other 3 occur 5/27ths.  Changing the one line as you suggested results in all 6 occurring 1/6th of the time +-.01%.

Excuse me.  I have to go do the math......
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.