Thread: Random but Unique Numbers

  1. #1
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215

    Random but Unique Numbers

    Hi

    i have a program that shows up random numbers here is the code that does this

    Code:
    #include <iostream>
    #include<cstdlib>
    #include <ctime>
    
    using namespace std;
    
    int main ()
    {
    
            srand((unsigned)time(NULL));
            int Rand[10]={0};
    
            for(int i=0;i<10;++i)
            {
                    Rand[i]=rand()&#37;11+1;
    
                    cout<<Rand[i]<<endl;
            }
    
            cin.get();
    }
    at the moment i get duplicate numbers. how can i get the program to check each number and if it is the same change it to another one so there are no duplicate numbers?

    Thanks
    Last edited by peckitt99; 11-14-2007 at 04:07 AM.

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Two ways:
    1. Generate a list of numbers and use STL's random_shuffle(). http://cppreference.com/cppalgorithm...m_shuffle.html

    2. Keep an array of booleans that is the size of the random numbers that is initialized to false, then set to true when a number is taken. If the entry is already true, take another number.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215
    is there any chance of an example of a boolean array - the reason i am asking this is because i need to create 2 random numbers like co-ordinates. and cant have any duplicates

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    bool array[10];
    Is that what you were looking for?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215
    yes - could you provide an example of how it can be used? obviously you not have to do it on my program - its just i havent used one before so i dont know how it works

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    bool is a type that can [1] hold two values "false" and "true".

    Say you want to know if you've seen a number before or not, in the range 0..9:
    Code:
    int main()
    {
        int x;
        bool arr[10];
    
        for(int i = 0; i < 10; i++) arr[i] = false;
        cout << "Type a number 0..9 (or -999 to exit):";
        for(;;) {
           cin >> x;
           if (x == -999) break;
           if (x > 9 || x < 0) {
              cout << "Invalid number, try again with 0..9:" << endl;
           }
           else 
           {
              if (arr[x]) {
                  cout << "Already typed " << x << endl;
              } 
              else 
              {
                   arr[x] = true;
              }
           }
        }
    }
    The above example has not been compiled, and is under no circumstances supposed to be a complete and fool-proof piece of code - but an example of how to use an array of boolean to indicate if something has been used or not?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215
    ok thanks - ill work with this and see if i can implement it into my random number generator.

  8. #8
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215
    well i have had a go - it might be completely wrong but i there are a few things that i am not sure about - if it is completely wrong please let me know where i am going wrong

    here is my new updated code

    Code:
    int main ()
    {
            bool arr[10];
            for(int j = 0; j < 10; j++) arr[j] = false;
    
            srand((unsigned)time(NULL)); // seed random number generator with system time
            int MyRand[10]={0}; // an array to store our random values;
    
              if (arr[MyRand[10]])
              {
                //not sure what to put here
              }
    
              else
              {
                    arr[MyRand[10]] = true;
            
                    for(int i=0; i<10; ++i)
                    {
                            MyRand[i]=rand()&#37;11+1; // get random number between 1 and 40 and store in array
                            cout<<MyRand[i]<<endl;
                    }
              }
    
    
            cin.get();
    
    }
    there is an error also which is a access voilation at this line

    Code:
    arr[MyRand[10]] = true;

  9. #9
    Registered User
    Join Date
    Nov 2007
    Posts
    12
    The error is because when you make an array, the first index is 0 (the number that goes in the [ ]). So an array of 10 would have indexes of 0 through 9.

    Also, you were on the right track the first time when it came up with duplicate numbers. You don't have to redo your entire code, only insert a few things.

  10. #10
    Is Trying to Learn
    Join Date
    Mar 2006
    Location
    Hutton, Preston
    Posts
    215
    ah right i see - well ill have another look - its confusing me and i bet it is something really simple :S

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Code:
                            MyRand[i]=rand()&#37;11+1; // get random number between 1 and 40 and store in array
    There are 3 bugs on this line. (Or 4 if you count the usage of % with rand)
    1. An off by one error since MyRand starts at 0 and the expression has a minimum of 1.
    2. Another off by one error since the right hand side generates numbers between 1 and 11 but the array only holds 10 items.
    3. The comment is wrong.

    So you're actually overstepping the bounds by 2 on that line.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by iMalc View Post
    There are 3 bugs on this line. (Or 4 if you count the usage of % with rand)
    1. An off by one error since MyRand starts at 0 and the expression has a minimum of 1.
    2. Another off by one error since the right hand side generates numbers between 1 and 11 but the array only holds 10 items.
    3. The comment is wrong.

    So you're actually overstepping the bounds by 2 on that line.
    No, he's indexing MyRand[i], and i goes from 0 to 9, so that's all fine. The random numbers are just values, not array indexes.

  13. #13
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Are you trying to get a random number between 1 and 40 or 1 and 10?

    If it's 1 and 10, then it looks like you really should be using matsp's first suggestion of random_shuffle. Even for 1 in 40 I'd probably use that method as well.

    Using random_shuffle makes sense when the range of numbers that you can pick from is not much bigger than the number of numbers you want to pick.

    If you want 10 random numbers in the range of [1, 40], then create an array (or vector) that holds the numbers 1 through 40. Then call random_shuffle on the array. The first ten numbers in the array are now your 10 random (but unique) numbers.

    This probably doesn't take up any more space than the bool array, but it might end up calling rand() a few more times internally (then again, with the bool array your worst case is infinite calls to rand()).

    If the range is really large, then I would use a set (or hash_set) to store the already chosen numbers. That's because the bool array would get too big.

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. Generating a sequence of numbers in a random order
    By mirbogat in forum C Programming
    Replies: 15
    Last Post: 08-12-2008, 02:01 PM
  3. Question about random numbers
    By Kempelen in forum C Programming
    Replies: 2
    Last Post: 07-02-2008, 06:28 AM
  4. Generating 100k to 1 million unique random numbers
    By Ariod in forum C Programming
    Replies: 4
    Last Post: 08-26-2005, 12:59 PM
  5. Help generating random numbers in MFC
    By drb2k2 in forum C++ Programming
    Replies: 3
    Last Post: 04-08-2003, 08:52 AM