poby
poby

Reputation: 1766

How to efficiently extract fixed length string permutations from a character list?

I'm trying to create a function that populates an array from a character list such that the array will be composed of n length unique strings. Every possible permutation should be included. The working example below uses n = 2 however I want to be able to vary n at runtime.

static char ULC[62] =   {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'};

static char pw[4096][2];    

for (int i = 0; i < 62; i++)
    {
    for (int j = 0; j < 62; j++)
        {
        pw[i * 62 + j][0] = ULC[i];
        pw[i * 62 + j][1] = ULC[j];
        }   
    }

Obviously increasing n will require a much larger array but I'm just using a static array in the above example to simplify the code and explanation. Ideally something that will work in visual studio C (not C++ and definitely not python, java etc).

Upvotes: 0

Views: 103

Answers (1)

Johnny Johansson
Johnny Johansson

Reputation: 270

If you rewrite it like this, it should be fairly simple to make it completely dynamic:

const int num_chars = 62;
const int n = 3;
static char pwn[num_chars * num_chars * num_chars][n];

for (int i = 0; i < num_chars * num_chars * num_chars; ++i) {
    int val = i;
    for (int in = 0; in < n; ++in) {
        pwn[i][in] = ULC[val % num_chars];
        val /= num_chars;
    }

}

Upvotes: 1

Related Questions