Thread: Generating 4 unique random numbers

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    21

    Question Generating 4 unique random numbers

    Hello,

    To begin with, i'm new to programming so try to keep it simple

    We're making a mastermind game at school, and i've done some of it already, but i need help with how to generate 4 unique random numbers, put into an array.

    I tried it out myself, and thought this code would work, but it didnt...

    Code:
    #include <stdio.h>
    #include <time.h>
    #define ARR_SIZE 4
    #define MAX 10
    
    int main()
    {
        int i;
        int j;
        int array[ARR_SIZE];
    
        srand(time(NULL));
    
        for(i=0; i<ARR_SIZE; i++)
        {
            array[i] = rand() % MAX;
    
            for(j=0; j<=(i-1); ++j)
                {
                    if (array[i] != array[j])
                        {
                            continue;
                        }
                    else
                        {
                            array[i] = rand() % MAX;
                        }
                }
        }
    
        return 0;
    }
    Maybe i misunderstood the "continue" command or something?

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    I dont really think you need to worry about the numbers repeating so soon if you are seeding the time.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Your inner loop should just be checking to see if there is a duplicate number.

    A bit of pseudo-code
    hasDuplicate = 0;
    for ( .... )
    if ( ... ) hasDuplicate = 1;


    If hasDuplicate is true, you need to generate another number (using the outer loop) at the SAME index (so no i++)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    21
    Quote Originally Posted by claudiu View Post
    I dont really think you need to worry about the numbers repeating so soon if you are seeding the time.
    its going from 0 to 10, so right now they duplicate almost every time...

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    If I make an int array, and populate it with incremented values, like so:

    Code:
    for(i=0;i<10;i++)
      matrix[i] = i;
    Now I have all unique numbers. The random part comes in the choosing of which number you want, by shuffling the array of numbers:
    Code:
    for(i=0;i<NumberOfSwapsYouWant;i++) {
      n = rand() % MAX;
      if(n != i)
        swap(matrix[i], matrix[n];
    }
    Why don't you try to code up a swap function or block of code for that?

    This is just like shuffling a deck of cards - and you can never have duplicates this way. (OK, you have to ditch that card up you sleeve, but it's best anyway)

    P.S. You can make the matrix array, any size you want, it doesn't have to be 10, and it doesn't have to be populated with 0 through MAX-1, either.

  6. #6
    Registered User
    Join Date
    Feb 2003
    Posts
    596
    Look again at your original code. When you find a duplication and generate a new value for a[i], your inner loop then proceeds to look for the new value of a[i] in the REMAINDER of the array -- ignoring the elements that it previously examined.

    For example, suppose you have the following array: [4, 2, 7, 3, 6] and you generate a 7 for a[5]. Your inner loop checks & finds a[0] is OK, a[1] is OK, a[2] is a duplicate so you generate a new a[5], which turns out to be a 4. Your inner loop now incorrectly assumes not only that
    (a) the new value isn't just another 7
    but also that
    (b) whatever the new value is, it is different from all of the elements previously checked

    That inner loop has to start over, checking the replacement value against every array element beginning at index 0. Add a line of code that resets j to -1 when you find a duplicated entry.

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Adak View Post
    This is just like shuffling a deck of cards - and you can never have duplicates this way.
    Actually when you need an array with all unique values in random order, the good old card shuffle is the way to go... Works real nicely on music playlists too...

  8. #8
    Programming King Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Middle of NoWhere
    Posts
    320
    Write break instead of continue.....

  9. #9
    THANK YOU KINDLY SIR Phenax's Avatar
    Join Date
    Mar 2011
    Posts
    74
    Unrelated but take notice that:
    Code:
    int x = rand() % 10;
    has a range of [0, 9]. Why? Because, the maximum remainder for division by 10 is 9. If you had a "remainder of 10", that would mean it's evenly divisible and thus no remainder.
    Quote Originally Posted by Plato
    Never discourage anyone...who continually makes progress, no matter how slow.

  10. #10
    Programming King Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Middle of NoWhere
    Posts
    320
    Quote Originally Posted by Phenax View Post
    Unrelated but take notice that:
    Code:
    int x = rand() % 10;
    has a range of [0, 9]. Why? Because, the maximum remainder for division by 10 is 9. If you had a "remainder of 10", that would mean it's evenly divisible and thus no remainder.
    Sorry but that's not an issue. Depends upon the programmer, what range of numbers he/she needs.
    And if it's divisible by 10, it's remainder will be 0.
    There is always a remainder for every number...

  11. #11
    Registered User
    Join Date
    Mar 2011
    Posts
    21
    Quote Originally Posted by Salem View Post
    Your inner loop should just be checking to see if there is a duplicate number.

    A bit of pseudo-code
    hasDuplicate = 0;
    for ( .... )
    if ( ... ) hasDuplicate = 1;


    If hasDuplicate is true, you need to generate another number (using the outer loop) at the SAME index (so no i++)
    Ahh, thanks, stupid me didnt think of that

    Now it works, and it might even be a simpler solution than the one the teacher showed us.


    Code:
    #include <stdio.h>
    #include <time.h>
    #define ARR_SIZE 4
    #define MAX 10
    
    int main()
    {
        int i;
        int j;
        int array[ARR_SIZE];
        int hasDuplicate;
    
        srand(time(NULL));
    
        for(i=0;i<ARR_SIZE;i++)
        {
            array[i] = rand() % MAX;
            printf("array[%d] = %d\n\n", i, array[i]);
            hasDuplicate = 0;
    
            for(j=0; j<=(i-1); j++)
                {
                    if (array[i] == array[j])
                    {
                        hasDuplicate = 1;
                        i--;
                    }
    
                }
        }
    
        return 0;
    }
    Thanks for the help, everyone!

    Another issue appeared when i tried to use the typedef thingie, i posted the code on pastebin so you could see which line the error is on... The code is here

    On line 17 it says: error: incompatible types when assigning to type 'Secret' from type 'int'

    And on line 42: error: passing argument 1 of 'fyllArray' from incompatible pointer type

    I didnt bother with translating the variable names, it should be pretty obvious anyway...

    I thought i did it the same way the teacher did it, but something is obviously wrong, hope you can help!
    Last edited by Newklear; 03-08-2011 at 05:10 AM.

  12. #12
    Registered User
    Join Date
    Mar 2011
    Posts
    21
    Ahh, found it... the [] in void fyllArray(Secret hemligtTal[]) caused the error, fixed it now!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. generating 10 unique random numbers in C
    By creeping death in forum C Programming
    Replies: 4
    Last Post: 01-28-2009, 11:23 AM
  2. random numbers
    By mesmer in forum C Programming
    Replies: 4
    Last Post: 10-24-2008, 01:22 PM
  3. random numbers
    By ballmonkey in forum C++ Programming
    Replies: 3
    Last Post: 01-18-2005, 02:16 PM
  4. Unique random numbers
    By aydin in forum C Programming
    Replies: 7
    Last Post: 11-23-2004, 12:21 PM
  5. generating random numbers within a range
    By tucky in forum C Programming
    Replies: 3
    Last Post: 09-14-2001, 12:59 PM