samedi 10 mars 2018

How to generate unique numbers in range 0001 - 2000 with rand() in C

I am trying to generate a dataset that has these two items: (i) a student ID containing values (0001 to 2000) generated from random and (ii) a corresponding age to the student ID (18 to 30). These random values are held in their respective array[1000] as you can see in Code

I am running into an issues with rand() where I have specified that I want to generate random numbers for the student ID from 1 to 2000 but I am running into what I think to be an issues of interger overflow. I think that the issues may be coming from one of the following:

  • My function is of type int, I may need to try a different type?
  • There is something wrong with the way I implemented my rand() % declaration
  • Some other problem that I am not aware of

You can see the issue I am having in Output

Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int createDataSet(void)
{
    srand(time(NULL));             // generates the random numbers

    int i = 0, x, p, count;

    char arrayId[1000];      // array that holds the ID's of 1000 students
    char arrayAges[1000];        // array that holds the ages of 1000 students

    for (count = 0; count < 1000; count++) // Init the "age" and "id" arrays
    {
        arrayId[count] = rand() % 2000 + 1;              // ID range 0001 - 2000
        arrayAges[count] = rand() % (30 + 1 - 18) + 18;   // Age range 18 - 30
    }

    while(i<1000){
        int r=rand() % (2000 + 1 - 0001) + 0001;

        for (x = 0; x < i; x++)
        {
            if(arrayId[x]==r){
                break;
            }
        }
        if(x==i){
            arrayId[i++]=r;
        }
    }

    for (p = 0; p < 1000; p++)
    {
        printf("ID Number: %d       Age: %d\n", arrayId[p], arrayAges[p]);
    }
    return 0;
}

Output:

ID Number: 115       Age: 28
ID Number: 104       Age: 21
ID Number: -113       Age: 25
ID Number: -3       Age: 18
ID Number: -41       Age: 20
ID Number: -94       Age: 28
ID Number: -4       Age: 19
ID Number: 4       Age: 28
ID Number: -112       Age: 23
ID Number: 33       Age: 20
ID Number: -119       Age: 30
ID Number: 12       Age: 23
ID Number: -96       Age: 27
ID Number: -88       Age: 30
ID Number: -105       Age: 20

My goal is to try and get the value in the array as seen in ID Number: to display random values between 1 to 2000 and be of unsigned type. Any help is appreciated. Thanks for your time!




Aucun commentaire:

Enregistrer un commentaire