Solved

array of random integers

Posted on 2003-11-29
15
1,223 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:Kent Olsen
ID: 9842339
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
ID: 9842515
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
ID: 9843902
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
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 

Expert Comment

by:junkjunkjunk
ID: 9845846
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:Kent Olsen
ID: 9846568

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
ID: 9866239
/* 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
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 9866446

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
ID: 10007976
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
ID: 10007988
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
ID: 10019710
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:Kent Olsen
ID: 10021657
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
ID: 10023486
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:Kent Olsen
ID: 10026384

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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
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 and use pointers in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

809 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