Re: thoughts on an approach

From: Roger Willcocks (roger_at_rops.org)
Date: 05/10/04


Date: Mon, 10 May 2004 01:37:57 +0100


"j0mbolar" <j0mbolar@engineer.com> wrote in message
news:2d31a9f9.0405071834.1972ecd2@posting.google.com...
> "Arthur J. O'Dwyer" <ajo@nospam.andrew.cmu.edu> wrote in message
news:<Pine.LNX.4.58-035.0405071753490.10956@unix50.andrew.cmu.edu>...
> > On Fri, 7 May 2004, Tim Van Wassenhove wrote:
...
> Sorry, my apologies. I should have posted the exact code
>
> for(i = 0; i < 255; ++i)
> for(j = 0; j < 255; ++j)
> for(k = 0; k < 255; ++k)
> for(l = 0; l < 255; ++l) {
> snprintf(buf, sizeof buf, "%d-%d-%d-%d", i, j, k, l);
> send_string(buf);
> }
>
> see how I have to permutate those values?
>
> I'm just wondering if there is a much
> cleaner approach without the need for
> four nested for loops

Here's an alternative method, but it's hard to beat the clarity of the
nested loops:

#include <stdio.h>

void recurse(int depth)
{
    static char prestring[20] = { 0 };
    char *slot;
    int i;

    if (depth == 4) {
        printf("%s\n", prestring + 1); /* skip leading '-' */
        return;
    }
    slot = prestring + strlen(prestring);
    for (i = 0; i < 256; i++) {
        sprintf(slot, "-%d", i);
        recurse(depth + 1);
    }
    *slot = 0;
}

int main(int argc, char* argv[])
{
    recurse(0);
    return 0;
}

--
Roger