mardi 29 octobre 2019

How to obtain an array without repeated values with one function

I want to create two arrays, none of them can have repeated values and if posible I look for an answer in the same loop.

for(int i=0;i<MAX;i++){//MAX=vector's number of values
            scanf("%d", &vector[i]);//reads the number from the keyboard
            while(j!=i){//Looks for each vector[i] if there is a vector[j], with j<i, with that value already. j starts at 0
                    if(vector[j]==vector[i]){
                            printf("\nWrite another number\n");
                            scanf("%d",&vector[i]);
                            j=0;
                    }
                    else
                            j++;
            }
    }

for this second loop I look for the same result, a non repeated set of values, but with random numbers.

for(int i=0;i<MAX;i++){
            vector[i]=(rand()%MAX-MIN+1)+MIN;
            while(j!=i){
                   if(vector[j]==vector[i]){
                            vector[i]=(rand()%MAX-MIN+1)+MIN;;
                            j=0;
                    }
                    else
                            j++;
            }
    }

I have been trying to come with a way to generate a random number between two intervals, like (2,10)U(12,20), so whenever you found a repeated value the next random number does not contain it, but I can not find any way to do it that way.

Thanks for your help




Aucun commentaire:

Enregistrer un commentaire