I recently began a personal project in C dealing with brute-force password cracking & encryption. I have been attempting to work on a function that outputs all possible combinations of the alphabet of length N. For example if N = 4, all possibilities from aaaa - zzzz would have to be outputted. Logically, I'm not understanding how I should approach this recursively.
char* alphabet[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
void passwords(int size){
char* password[size];
char* result;
//Determining static letter
for(int i = 0; i < size; i ){
for(int x = 0; x < size; x ){
password[x] = "a";
}
int index = i 1; //password index to modify
while(index < size){
for(int j = 0; j < 26; j ){
password[i] = alphabet[j];
printf("%s\n",password);
}
index ;
}
}
}
int main(int argc, char* argv[]){
passwords(3);
return 0;
}
Currently this program only modifies one character of the alphabet and produces an output of:
aaa
baa
caa
daa
...//e-z aa
aaa
aba
aca
ada
...//a e-z a
aaa
aab
aac
aad
...//aa e_z
Any suggestions would be great thanks!
CodePudding user response:
If the usage of recursion is not the mandatory requirement, would you please try:
#include <stdio.h>
#include <stdlib.h>
#define N 26 // number of alphabets
void passwords(int size) {
int i;
char *password;
if (NULL == (password = malloc(size 1))) {
perror("malloc");
exit(1);
}
for (i = 0; i < size; i ) {
password[i] = 'a'; // initialize the array
}
password[i] = '\0'; // terminate the string
while (1) {
printf("%s\n", password);
password[size - 1] ; // increment rightmost character
for (i = size - 1; i >= 0; i--) {
if (password[i] >= 'a' N) { // carry over
if (i == 0) { // end of permutation
free(password);
return;
} else {
password[i] = 'a';
password[i - 1] ;
}
}
}
}
}
int main()
{
passwords(3);
return 0;
}