Return to Snippet

Revision: 61181
at December 2, 2012 12:41 by rtperson


Initial Code
int countInTernary(int numdigits) {
    char num[numdigits+1];
    memset(num, '0', sizeof num);
    num[numdigits] = 0;
    char *curIndex = &num[numdigits-1];
    char *end = &num[numdigits-1];
    char *start = &num[0];
    bool done = false;
    
    while (!done) {
        printf("%s\n", num);
        if (*curIndex < '2') {
            (*curIndex)++;
        } else {
            /* move left until you find a number < 2 */
            while (curIndex >= start && *curIndex == '2') {
                --curIndex;
            }
            if (curIndex < start) {
                done = true;
            } else {
                (*curIndex)++;
                while (curIndex < end) {
                    curIndex++;
                    *curIndex = '0';
                }                
            }
        }
    }  
    return EXIT_SUCCESS;
}

Initial URL

                                

Initial Description
Here's a fairly useless but fun piece of code: counting in base 3. This takes in a number of  digits and counts up in ternary. Be warned, though. The algorithm is (for obvious reasons) O(n^3), where n is the number of digits. Actually probably theta(n^3), since n^3 is both the upper and lower bound. Either way, it spits out 531,441 possibilities for 12 digits, so be careful not to run it on too many digits.

Initial Title
Ternary Counting In C

Initial Tags

                                

Initial Language
C