Solved

array of random integers

Posted on 2003-11-29
15
1,217 Views
Last Modified: 2010-05-18

How can I create a function to fill an array with random integers between 1 and 100?
0
Comment
Question by:alertel
  • 5
  • 2
  • 2
  • +4
15 Comments
 
LVL 45

Expert Comment

by:Kdo
Comment Utility
Hi alertel,

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
 
LVL 1

Expert Comment

by:imstaff
Comment Utility
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
 
LVL 15

Accepted Solution

by:
efn earned 20 total points
Comment Utility
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
 

Expert Comment

by:junkjunkjunk
Comment Utility
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
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

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
 
LVL 22

Expert Comment

by:earth man2
Comment Utility
/* 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 45

Expert Comment

by:Kdo
Comment Utility

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
 

Expert Comment

by:Gingit
Comment Utility
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.

Please help.

G.
0
 

Expert Comment

by:Gingit
Comment Utility
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
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Instead, use
other_idx =  rand() % (idx+1);
0
 
LVL 45

Expert Comment

by:Kdo
Comment Utility
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
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
 
LVL 45

Expert Comment

by:Kdo
Comment Utility

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

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now