lundi 22 février 2021

How to generate non-repeating numbers in C?

my first post here.

I'm trying to write a program in C, which generates a random password made of numbers, letters and capitals. The problem is that characters in password must NOT be repeated. I tried a few ways to prevent that, but nothing seemed to work.

void createPassword() {
char password[LENGTH];
char nums[] = "0123456789";
char letters[] = "abcdefghijklmnopqrstuvwxyz";
char caps[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int selector = rand() % 3; //random choice of character type
int i;

printf("Vytvorene heslo: ");
for(i = 0;i < LENGTH;i++) {
    if(selector == 1) { //if selector == 1, add number to password etc.
        password[i] = nums[rand() % 10];
        printf("%c", password[i]);
        selector = rand() % 3;
    }
    else if(selector == 2) {
        password[i] = letters[rand() % 26];
        printf("%c", password[i]);
        selector = rand() % 3;
    }
    else { 
        password[i] = caps[rand() % 26];
        printf("%c", password[i]);
        selector = rand() % 3;
    }
}}

I'll be glad if someone could tell me what to do next.




Aucun commentaire:

Enregistrer un commentaire