Logic to select a specific set from Cartesian set

雨燕双飞 提交于 2019-12-20 04:12:04

问题


I'm making a password brute forcing tool as a learning exercise, and I want it to be resumable.

So, what I want is to be able to say, this is the set of possible characters, if I computed the Cartesian set of every possible combination of this set up to length n, what is the set at point x?

However, I want to do this without computing the entire set. I've seen similar logic in one place online but I was unable to generalise this to fit.

Any help would be fantastic, thanks! I'm fluent in C# if that helps.

Edit: Here's the question I mentioned earlier: How to select specific item from cartesian product without calculating every other item

Edit: here's an example of what I mean:

Char set = [abcd]

Length n = 4

Permutations:

[aaaa]
[aaab]
[aaac]
[aaad]
[aaba]
....
[dddd]

So if I'm searching for the set at 4, I'd get [aaad]. But if I'm searching for element 7000, then it takes a long time to get to that point.


回答1:


This implements the answer to the question you link:

static string Get(string chars, int n, int i)
{
    string ret = "";
    int sizes = 1;
    for (int j = 0; j < n; j++) {
        ret = chars[(i / sizes) % chars.Length] + ret;
        sizes *= chars.Length;
    }
    return ret;
}

Example:

string chars = "abcd";
int n = 3;

for (int i = 0; i < Math.Pow(chars.Length, n); i++)
    Console.WriteLine(i + "\t" + Get(chars, n, i));
0       aaa
1       aab
2       aac
3       aad
...
61      ddb
62      ddc
63      ddd


来源:https://stackoverflow.com/questions/22269598/logic-to-select-a-specific-set-from-cartesian-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!