Create a vector with srand without repeating numbers in C

Asked

Viewed 172 times

0

I am creating a vector with random numbers from 1 to 60 using the Rand function. This vector cannot contain repeated numbers. For example, if srand’s return was number 3, and there is already a number 3 in the vector, I need to generate another random number and redo the check. But I’m not sure how to do that repetition.

For now I’ve done it:

    int vetor[30]={0};  //preciso de 30 valores aleatorios diferentes, aqui o vetor está cheio com zeros

    candidato = 1+rand()%59; //variavel que armazenará o valor a ser testado
  • 1

    Set up an array with 60 numbers from 1 to 60, shuffle this array and take the first 30 numbers, copying them to another array. The shuffling algorithm is the Fisher-Yates.

  • Perfect! Much more optimized than creating auxiliary vectors or scrolling through to check every time. Thanks @Victorstafusa

1 answer

-3

Draw on this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    int numero[50], i, j;
    char ja_consta;
    srand(time(NULL));
    for (i=0; i<50; i++) {
        numero[i] = rand() % 100 + 1;
        ja_consta = 'N';
        for (j=0; j<i && ja_consta == 'N'; j++) {
            if (numero[i] == numero[j])
                ja_consta = 'S';
        }
        if (ja_consta == 'S')
            i--;
    }
    for (i=0; i<50; i++)
        printf("\t%d", numero[i]);
    return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.