Like Tree7Likes

Help!! trying to get 6 random numbers

This is a discussion on Help!! trying to get 6 random numbers within the C Programming forums, part of the General Programming Boards category; when i compile it, i get the 6 random numbers upto 49. after few tries, sometimes I get the same ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    23

    Post Help with rand..

    when i compile it, i get the 6 random numbers upto 49. after few tries, sometimes I get the same numbers !! so how do i fix this?
    Code:
    #include <stdio.h>
    #include <math.h>
    #include <time.h>
    #include <stdlib.h>
    int main (void)
    {
    int a, b, c, d, e, f;
    // print title
    printf("*** 6/49 LOTTERY PICKER ***\n");
    
    
    // seed generator with time of day
    srand(time(NULL));
    a= rand()%49+1;
    b= rand()%49+1;
    c= rand()%49+1;
    d= rand()%49+1;
    e= rand()%49+1;
    f= rand()%49+1;
    
    
    printf("My Lucky Numbers Are %d, %d, %d, %d, %d, %d\n", a, b, c, d, e, f);
    
    
    return 0;
    Last edited by blackendstars; 01-31-2013 at 04:16 PM.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,427
    What do you mean by "same numbers"? Do you sometimes get the exact same list of numbers, for a-f? Or do you get a single number that is repeated in the set of lottery numbers?

    If you get the the exact same numbers for all six lottery numbers, consider this: time(NULL) only gives you time to the nearest second. Thus if you run your program twice in the same second, srand() gets the same seed value and thus repeats the sequence. Remember, it only produces pseudo-random numbers.

    If you get a single number (or two perhaps) repeated, then you must realize that is the nature of a random (or pseudo-random) number generator. It may repeat a number from time to time. Sometimes the space between a number and a repeat of that number is quite small, only a few numbers in between. This problem is made worse by the fact that you use modulo 49 (% 49), since it takes the ~4 billion possible values and squishes them all into one of 49 boxes. That really increases the chance of a repeat. There is a solution to this, which is pretty easy.

    Simply store the numbers for your lottery in an array of ints. Then, shuffle that array (Fisher), and pick the first six numbers. A small example, picking 3 of 6:
    Code:
    [1, 2, 3, 4, 5, 6]
    // shuffle it
    [3, 1, 6, 4, 5, 2]
    // picking the first 3 gives
    3, 1, 6
    Salem likes this.

  3. #3
    Registered User
    Join Date
    Nov 2012
    Posts
    1,053
    Rather than time(NULL), you can ask the standard library for the time in microseconds. This value is very unlikely to be the same between two invocations of your program.

    Code:
    struct timeval tp;
    gettimeofday(&tp, NULL);
    unsigned long micros = tp.tv_sec * 1000000;
    micros += tp.tv_usec;
    srand((unsigned)(micros % UINT_MAX));

  4. #4
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,323
    Fact - Beethoven wrote his first symphony in C

  5. #5
    Registered User Kain's Avatar
    Join Date
    Nov 2012
    Posts
    17
    I use this code for random numbers, and up until now it seems to work pretty well. :-)

    Code:
    #include <ctime>
    #include <cstdlib>
    #include <iostream>
    using namespace std;
    
    bool random = true;
    
    int r( int r1 , int r2 )
    {
        if( random )
        {
            srand( ( int ) time ( 0 ) );
            random = false;
        }
    
        int r3 = rand();
        return r3 = rand() % ( r2 - r1 + 1 ) + r1;
    }
    
    int main()
    {
        cout << r( 1 , 40 ) << endl;
        cout << r( 1 , 40 ) << endl;
        cout << r( 1 , 40 ) << endl;
    
        cin.get();
        return 0;
    }
    I'm still a beginner at programming, though, so the code might be a bit crude.
    I hope it helps you, though. :-)

  6. #6
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,323
    Quote Originally Posted by Kain View Post
    I use this code for random numbers, and up until now it seems to work pretty well. :-)

    Code:
    #include <ctime>
    #include <cstdlib>
    #include <iostream>
    using namespace std;
    
    bool random = true;
    
    int r( int r1 , int r2 )
    {
        if( random )
        {
            srand( ( int ) time ( 0 ) );
            random = false;
        }
    
        int r3 = rand();
        return r3 = rand() % ( r2 - r1 + 1 ) + r1;
    }
    
    int main()
    {
        cout << r( 1 , 40 ) << endl;
        cout << r( 1 , 40 ) << endl;
        cout << r( 1 , 40 ) << endl;
    
        cin.get();
        return 0;
    }
    I'm still a beginner at programming, though, so the code might be a bit crude.
    I hope it helps you, though. :-)
    That is C++ code

    This is a C thread :P
    hex_dump likes this.
    Fact - Beethoven wrote his first symphony in C

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,288
    Quote Originally Posted by c99tutorial View Post
    Rather than time(NULL), you can ask the standard library for the time in microseconds. This value is very unlikely to be the same between two invocations of your program.
    That's unlikely to be the problem here. This is code for a "LOTTERY PICKER", which indicates that his problem is in wanting unique values rather than what he has at the moment which will obviously produce duplicates on occasion.

    blackendstars, I put the question to you, what ways can you think of to ensure that there are no duplicates? What would you do if you were getting the numbers by rolling 49-sided dice (if such a thing existed) and wanted them to be unique?
    laserlight likes this.
    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"

  8. #8
    Registered User
    Join Date
    Jan 2013
    Posts
    7
    Code:
    #include <stdio.h>
    #include <time.h>
    
    int main()
    {
        srand((unsigned)time(NULL));
        int numbers,loop;
    
        for(loop=1;loop<=6;loop++)
    {
        numbers=rand()%49+1;
        printf("Random #%d = %d\n",loop,numbers);
    
    }
    return(0);
    }

  9. #9
    Registered User
    Join Date
    Nov 2012
    Posts
    1,053
    If you want N unique random numbers, a simple way is the following

    1. Make an empty list capable of holding N items.
    2. Generate a random number x.
    3. If x does not exist in L, then: add x to L.
    4. Go to 2.

    Break the loop after you have added N items to L. For example, you can use a while loop with a counter that increments each time you successfully find a new random number. For this strategy to work, the range of valid random numbers must be large compared to N. If N gets too large, this strategy has a high probability of getting "stuck" in the loop.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,311
    Quote Originally Posted by c99tutorial
    If N gets too large, this strategy has a high probability of getting "stuck" in the loop.
    In which case you would be better off generating the entire range, then shuffling to obtain the N numbers.
    Click_here likes this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Jan 2013
    Posts
    7
    You guys are making it seem way too complicated.

  12. #12
    Registered User
    Join Date
    Jun 2011
    Posts
    2,197
    Quote Originally Posted by LTA85 View Post
    You guys are making it seem way too complicated.
    I don't think you understand the problem.

    Your program in post #8 is a simple example of finding six random numbers within a certain range.

    However, the OPs requirements seem to include making sure there are no duplicate numbers. That is a little bit more involved.

    Note that this was already mentioned by iMalc in the post above yours (post #7).
    laserlight likes this.

  13. #13
    Registered User
    Join Date
    Nov 2012
    Posts
    1,053
    If you want to use the shuffle method, you can do it simply using qsort and a compar function that returns -1 or 1 randomly

    Code:
    int cointoss_compar(const void *a, const void *b) {
        (void)a; // ignore these
        (void)b;
        return rand() < (RAND_MAX/2) ? -1 : 1;
    }
    
    void shuffle(int *arr, int n) {
         qsort(arr, n, sizeof(*arr), cointoss_compar);
    }
    
    int main(void) {
        int numbers[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        shuffle(numbers, 10);
        print(numbers, 10);
        return 0;
    }

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,311
    Quote Originally Posted by c99tutorial
    If you want to use the shuffle method, you can do it simply using qsort and a compar function that returns -1 or 1 randomly
    No point though since implementing a basic version Fisher-Yates/Knuth shuffle is not that hard, especially with the help of online resources.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,288
    Quote Originally Posted by c99tutorial View Post
    If you want to use the shuffle method, you can do it simply using qsort and a compar function that returns -1 or 1 randomly
    Actually, that's rather dangerous. It's implementation dependent of course, but I know that the partition technique I've used at times avoids having multiple conditions in the innermost loops because it assumes that you can't go through the entire array without hitting an element that is not greater than the splitter. (I.e. you when it runs into the splitter itself). Violating this assumption could cause it to run off the end of the buffer.

    Even more importantly, make sure you don't do this in C++ using std::sort. You risk not only causing the above, but also violate the strict-weak-ordering assumption that std::sort has, which it may well pull you up on in a debug build.
    whiteflags likes this.
    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"

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Will we ever have truly random numbers?
    By jalnewbie in forum C Programming
    Replies: 7
    Last Post: 11-30-2006, 01:14 PM
  2. Replies: 4
    Last Post: 11-16-2004, 06:29 AM
  3. Random Numbers
    By glider_pilot123 in forum C Programming
    Replies: 4
    Last Post: 11-03-2004, 01:12 PM
  4. Replies: 10
    Last Post: 11-23-2001, 09:01 AM
  5. Random Numbers
    By Estauns in forum C++ Programming
    Replies: 2
    Last Post: 11-18-2001, 06:30 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21