vendredi 12 novembre 2021

Random characters from array without repetition

I try to create a program in C that selects random characters from the array and stores them in the second array but without repetition.

Code:

int main(){
    srand ( time(NULL) );
    char characters[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};
    char array[20];
    int size = strlen(array);

    int random, random_character;

    for(int i = 0; i < rows; i++){
        random_character= rand() % rows;
        random = characters[random_character];
        array[i] = random;
        for(int j = 0; j < 4; j++){
            if(array[i] == array[j]){
                array[i] = random;
            }
        }
    }

    for(int i = 0; i < 4; i++){
        printf("%c ", array[i]);
    }
}

My output still has at least two equal characters.




Aucun commentaire:

Enregistrer un commentaire