samedi 2 novembre 2019

How do I generate random numbers but not repeating and within a certain range based on user input?

Currently, I am experimenting some codes regarding/about random numbers. The problem is, when I run the program, input any number (ex. 12), I, sometimes get the correct and sometimes wrong answer. The correct answer must be any non repeating random numbers based on user input. (ex. input 5, output must be 1. seats[12]=1, 2. seats[19]=1,..., 5. seats[47]=1). I do not know what to do and yeah help me coders!

Here's the code:

#include<stdio.h> 
#include<conio.h>
#include<time.h>
main()
{
    int x,y,chc1A,seats[50]={};
    printf("Enter a number: ");
    scanf("%d",&chc1A);
    srand(NULL);
    for(x=0;x<chc1A;x++)
    {
        if(seats[rand()%50]==0)
            seats[rand()%50]=1;
        else
            x--;
    }
    for(x=0,y=1;x<50;x++)
        if(seats[x]==1)
        {
            printf("%d. seats[%d] = %d\n",y,x,seats[x]);
            y++;
        }
    getch();
}

I do not really know what's wrong please enlighten me.

I run and coded this on Dev C++

What I want to do is: generate random numbers between 0-49 and putting it in an array seats[50]. (ex 38 then put 1 in array seats[38]). Btw this code represents passengers sitting on a bus with 50 seats. So the "1" means that the seat is occupied.




Aucun commentaire:

Enregistrer un commentaire