//

//  main.m

//  test

//

//  Created by mac on 16-3-1.

//  Copyright (c) 2016年 _MyCompany_. All rights reserved.

//

 

#import <Foundation/Foundation.h>

 

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

 

static const char alphabet[] =

"abcdefghijklmnopqrstuvwxyz"

"ABCDEFGHIJKLMNOPQRSTUVWXYZ"

"0123456789";

 

static const int alphabetSize = sizeof(alphabet) - 1;

 

void bruteImpl(char* str, int index, int maxDepth)

{

    for (int i = 0; i < alphabetSize; ++i)

    {

        str[index] = alphabet[i];

        

        if (index == maxDepth - 1) printf("%s\n", str);

        else bruteImpl(str, index + 1, maxDepth);

    }

}

 

void bruteSequential(int maxLen)

{

    char* buf = malloc(maxLen + 1);

    

    for (int i = 1; i <= maxLen; ++i)

    {

        memset(buf, 0, maxLen + 1);

        bruteImpl(buf, 0, i);

    }

    

    free(buf);

}

 

static const int BUFFLEN=1024*100;

void brute2(int maxLen)
{
    char* indices = malloc(maxLen + 1);
    char* terminal = indices+maxLen;
    char *printbuff = malloc(BUFFLEN);
    char *pbend = &printbuff[BUFFLEN-1];
    char *b = printbuff;
    *pbend = '\0';
    ++indices[0];
    char *p;

    while (*terminal == 0) {
        // print value
        for (p = indices; *p; ++p)
            ;
        for (--p ; p >= indices; --p) {
            *b++ = alphabet[*p-1];
            if (b == pbend) {
                fwrite(printbuff, 1, b-printbuff, stdout);
                b = printbuff;
            }
        }
        *b++ = '\n';
        if (b == pbend) {
            fwrite(printbuff, 1, b-printbuff, stdout);
            b = printbuff;
        }
        // increment values
        int carry = 1;
        for (++p ; carry; ++p) {
            if ((*p += carry) > alphabetSize) {
                *p = 1;
                carry = 1;
            } else {
                carry = 0;
            }
        }
    }
    fwrite(printbuff, 1, b-printbuff, stdout);

    free(indices);
    free(printbuff);
}

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        // insert code here...

         bruteSequential(8);

    }

    return 0;

}