简体   繁体   中英

How to generate an array of random & unique integers in C?

I am creating a C-prog that requires an array of 17 integers, all being less than 18 and unique. This is what I could do until now:

int ques_arr[17];
int x,y;
time_t t;
srand((unsigned)time(&t));

for(int a=0; a<17; a++)
{
x=rand()%18; //Assume that srand() has been declared in the program
 for(int aa=0; aa<17; aa++)
 {
  if(x==ques_arr[aa])
   { do{
        y=0;
        y=rand()%18;
        }while(y==ques_arr[aa]);
      x=y; 
      ques_arr[a]=x;
    }else ques_arr[a]=x;
  }
}

My current algorithm is that everytime rand() generates a number, that number will be checked throughout array whether same number already exists or not, if it does, rand() keeps on generating a number until a unique number is obtained and then it is stored in the array.If such a number doesn't exist in the array, it's directly fed in to it.

As of now, numbers stored in the array are not unique.

Any help would be appreciated.

This is not an optimal solution, your time complexity once you have fixed the problem in your code is O(n²), you can reduce the time complexity to O(n) using the "Knuth Shuffle algorithm":

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

static int rrand(int value)
{
    return (int)((double)value * (rand() / (RAND_MAX + 1.0)));
}

static void randomize(int arr[], int size)
{
    for (int idx = 0; idx < size; idx++)
    {
        arr[idx] = idx;
    }
    for (int idx = size; idx > 1; idx--)
    {
        int num = rrand(idx);
        int tmp = arr[idx - 1];

        arr[idx - 1] = arr[num];
        arr[num] = tmp;
    }
}

int main(void)
{
    srand((unsigned)time(NULL));

    int arr[17] = {0};
    int size = sizeof arr / sizeof *arr;

    randomize(arr, size);
    for (int idx = 0; idx < size; idx++)
    {
        printf("%d\n", arr[idx]);
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM