MD XF
MD XF

Reputation: 8129

How would I shorten these for loops?

So I've got a program that runs through every possible alphanumerical combination between 0000000000 and ZZZZZZZZZZ. Currently I'm using this code:

for (digit[0] = 0; digit[0] < 36; digit[0]++)
    for (digit[1] = 0; digit[1] < 36; digit[1]++)
        for (digit[2] = 0; digit[2] < 36; digit[2]++)
            // etc...

...and eventually there are 10 nested for loops and my entire editor screen is filled. So how would I condense this into one or two for loops? I can't find out how I would put them together testing and incrementing digit[i]. Thanks in advance to anyone who has this solution. I bet there's a million webpages on this but I couldn't think of how to phrase it in a google search.

Upvotes: 0

Views: 108

Answers (2)

anonymoose
anonymoose

Reputation: 868

Here's one solution that uses a recursive function. You may have to adapt it slightly, as I had to assume some things - like the type of the array you're using.

Also, be warned that this will overflow if the for loop runs just one too many times.

void incDigit(int *digits) {
  digits[0]++;
  if(digits[0] >= 36) {
    digits[0] = 0;
    incDigit(digits + 1);
  }
}

int digits[10];
int i, j;
for(i = 0; i < (int)pow(36, 5); i++) {
  for(i = 0; i < (int)pow(36, 5); i++) {
    //Code here  
    incDigit(digits);
  }
}

Upvotes: 0

Barmar
Barmar

Reputation: 781726

Use an odometer algorithm. Increment the last digit. When it reaches the highest value, wrap it back to 0 and recurse on the remaining digits, until you run out of digits.

int increment_digit(int array[], unsigned int index, limit) {
    if (index == -1) { // We've wrapped around the entire set
        return 0;
    }
    array[index]++;
    if (array[index] == limit) {
        array[index] = 0;
        return increment_digit(array, index-1, limit);
    } else {
        return 1;
}

int main(int argc, char **argv) {
    int digits[SIZE] = {0};
    while (1) {
        // do stuff ...
        if (!increment_digit(digits, SIZE-1, 36))
            break;
        }
    }
    return 0;
}

Upvotes: 2

Related Questions