// Print all combinations of the given alphabet up to length n. // // Example: length 3 combinations are: // // aaa // aab // aac // ... // aa9 // aba // abb // abc // ... // a99 // baa // bab // ... // 998 // 999 // // The best way to test this program is to output to /dev/null, otherwise // the file I/O will dominate the test time. // // This is the same as alphabet.c except this version uses 3 hardcoded // letters instead of 2. #include #include #include #include const char *alphabet = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; static void generate(int maxlen); int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s Length\n", argv[0]); exit(1); } generate(atoi(argv[1])); return 0; } /** * Generates all patterns of the alphabet up to maxlen in length. This * function uses a buffer that holds alphaLen^3 patterns at a time. * One pattern of length 5 would be "aaaaa\n". The reason that alphaLen^3 * patterns are used is because we prepopulate the buffer with the last 3 * letters already set to all possible combinations. So for example, * the buffer initially looks like "aaaaa\naaaab\naaaac\n ... aa999\n". Then * on every iteration, we write() the buffer out, and then increment the * fourth to last letter. So on the first iteration, the buffer is modified * to look like "abaaa\nabaab\nabaac\n ... ab999\n". This continues until * all combinations of letters are exhausted. */ static void generate(int maxlen) { int alphaLen = strlen(alphabet); int len = 0; char *buffer = malloc((maxlen + 1) * alphaLen * alphaLen * alphaLen); int *letters = malloc(maxlen * sizeof(int)); if (buffer == NULL || letters == NULL) { fprintf(stderr, "Not enough memory.\n"); exit(1); } // This for loop generates all 1 letter patterns, then 2 letters, etc, // up to the given maxlen. for (len=1;len<=maxlen;len++) { // The stride is one larger than len because each line has a '\n'. int i; int stride = len+1; int bufLen = stride * alphaLen * alphaLen * alphaLen; if (len == 1) { // Special case. The main algorithm hardcodes the last two // letters, so this case needs to be handled separately. int j = 0; bufLen = (len + 1) * alphaLen; for (i=0;i= alphaLen) letters[i] = 0; // Set this letter in the proper places in the buffer. c = alphabet[letters[i]]; for (j=i;j