Draw of numbers with exception
How do I draw a quantity n
of numbers in the C language where I can exclude the possibility of drawing a certain number from my range given a certain 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;
}
2
2 answers
Following the same reasoning of Mr Maniero, I suggest you repeat the sampling until you get a valid value. See the code below.
Note: you should use srand
to initialize the sampling to obtain different values each 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]);
}
}
3
Author: Nino Pereira, 2019-09-20 12:29:23
You need to be drawing the number until you get one that doesn't interest you. There are other solutions, but for such a simple cases have no reason 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 working on ideone. E no repl.it. also I put on GitHub for future reference .
2
Author: Maniero, 2020-11-13 19:49:25