Unique random function without repetition - C language

Asked

Viewed 324 times

0

Guys, I’m doing a program in C language, and I need him to do some sweepstakes, but they can’t be repeated, the program controls the input of a lecture, and there will be a draw, in this draw the same numbers can’t be drawn, I’m drawing lots for each row and chair. simulating 30 rows and 60 chairs in each row, I even managed to do the draw, but I’m not getting the repetitions out. Follow the code of what I did, but it didn’t work:

void sorteio(int cadeiras[30][60], dados cadastro[3]){

    int a,b,c,d,f[30],p[60],i=0;

    do{
        cadeiras[c=(rand() % 29)][d=(rand() % 59)];
        for (a=0; a>29; a++){
            if(f[a]!=c){
                for (b=0; b>59; b++){
                    if(p[b]!=d){
                        if(cadeiras[c][d]==1){
                            f[i]=c;
                            p[i]=d;
                            i++;
                            printf("\n %d Os sorteado foram: %d fileira %d cadeira", i,c,d);
                        }
                    }
                }
            }
            else{
                for (b=0; b>59; b++){
                    if(p[b]!=d){
                        if(cadeiras[c][d]==1){
                            f[i]=c;
                            p[i]=d;
                            i++;
                            printf("\n %d Os sorteado foram: %d fileira %d cadeira", i,c,d);
                        }
                    }
                }
            }
        }
        //if()
        //if(cadeiras[c][d]==1){
          //  i++;
          //  printf("\n %d Os sorteado foram: %d fileira %d cadeira", i,c,d);
       // }
    }while(i!=15);
}
  • To ensure that random numbers are generated without repetition you need to store all the numbers already generated and each new number will only be accepted if it is not already in the list of stored.

  • Yes, I thought about it, but I’m not getting a way to efficiently store it, I’m going to edit the question and put the code

  • Here: chairs[c=(Rand() % 29)][d=(Rand() % 59)]; should be: chairs[c=(Rand() % 30)][d=(Rand() % 60)];. Your stop condition on the controls is wrong.

  • For your case I believe you should generate rows and chairs until all are marked as occupied.

No answers

Browser other questions tagged

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