Thread: random numbers

  1. #1
    Registered User
    Join Date
    Dec 2005
    Location
    Canada
    Posts
    267

    random numbers

    I know how to get a random number and set the seed. My problem herre is I have an array of 50 numbers and i want to give them all random numbers in a for loop or some simple way where i wouldn't have to write something for each one but I can't make them random enough.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >My problem herre is I have an array of 50 numbers and i want to give them all random numbers in a for loop
    Is this what you mean?
    Code:
       int array[50];
       for (int i=0; i<50; i++)
       {
          //Insert your code to generate a random number here
          array[i] = number generated above;
       }
    
       //Print them out
       for (int i=0; i<50; i++)
       {
          std::cout << array[i] << std::endl;
       }

  3. #3
    One line at a time... Tsunexus's Avatar
    Join Date
    Dec 2005
    Location
    north carolina
    Posts
    4
    heres another way to do it... i dont know what your using but i use Turbo C so i'd have to include stdlib.h... but i dunno if you do to use the rand() function
    Code:
    int array[50];
    int minrand=20; //minimum random number
    int maxrand=50; //maximum random number
       for (int i=0; i<50; i++)
       {
          array[i] = (rand()%(maxrand+1-minrand))+minrand;
       }
    does that make sense? lol... its an easier way to set the borders on the random number... i figured it might help >.<

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If the numbers can be duplicated, then a simple loop would work fine. If the numbers should be unique, like randomly shuffling the numbers from 1-50 that are in the array, then the solution is to fill the array in order without using rand(), then use random_shuffle() to shuffle the array. If you cannot use something from <algorithm> to do the work for you, then you can use the same technique as random_shuffle uses to get the effect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. questions....so many questions about random numbers....
    By face_master in forum C++ Programming
    Replies: 2
    Last Post: 07-30-2009, 08:47 AM
  2. Doubts regarding random numbers generation
    By girish1026 in forum C Programming
    Replies: 9
    Last Post: 12-31-2008, 10:47 PM
  3. random numbers limit
    By HAssan in forum C Programming
    Replies: 9
    Last Post: 12-06-2005, 07:51 PM
  4. Generate random numbers in Lucky7 project using C#
    By Grayson_Peddie in forum C# Programming
    Replies: 1
    Last Post: 04-11-2003, 11:03 PM
  5. random numbers
    By lil_plukyduck in forum C++ Programming
    Replies: 5
    Last Post: 01-14-2003, 10:14 PM