Number draw with exception

1

How do I sort a% number of% numbers in the C language in which I can exclude the possibility of drawing a certain number from my range given a given condition?

Exemplifying in code:

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

int main(void)
{
     int i,;
     int x[8];

     printf("Gerando 10 valores aleatorios:\n\n");
     for(i=0;i<8;i++){
        scanf("%d", &x[i]);
        if(x[i]==3){
                x[i] = rand()% 8 ("com exceção do i");
            }
        }
     }

     return 0;
}
    
asked by anonymous 16.11.2016 / 17:11

2 answers

2

Following the same rationale as my colleague bigown, I suggest that you repeat the sampling until you get a valid value. See the code below. Note: You should use srand to initialize the sampling so that you get different values every time you run the program.

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

int main(void) {
    int x[8];

    srand(time(NULL));
    printf("Gerando 10 valores aleatorios:\n");
    for (int i = 0; i < 8; i++) {
        scanf("%d", &x[i]);
        if (x[i] == 3) {
            int sorteado = rand() % 8;
            while (sorteado == i){
                printf("recusado: %d ",sorteado);
                sorteado = rand() % 8;
            }
            printf("sorteado = %d \n",sorteado);    
            x[i] = sorteado;
        }
        printf("[%d] = %d\n", i, x[i]);
    }
}

Solution here: link

    
17.11.2016 / 10:55
2

You need to keep drawing the number until you get one that does not interest you. There are other solutions, but for a simple case it does not have to complicate. It would be this:

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

int main(void) {
    int x[8];
    printf("Gerando 10 valores aleatorios:\n");
    for (int i = 0; i < 8; i++) {
        scanf("%d", &x[i]);
        if (x[i] == 3) {
            int sorteado = -1;
            while ((sorteado = rand() % 8) != i); //repete até achar um valor aceitável
            x[i] = sorteado;
        } else {
            x[i] = rand() % 8;
        }
        printf("[%d] = %d\n", i, x[i]);
    }
}

See running on ideone and on CodingGround .

    
17.11.2016 / 00:16