小编典典

算法:里程表/蛮力

algorithm

我想用C#风格的语言编写类似里程表的方法,但不仅要使用0-9的字符,还要使用任何字符集。或多或少,它将像蛮力的应用程序一样。

如果我输入从 0J 的字符数组,并将长度设置为5,我想要的结果是 00000,00001,00002 …
HJJJJ,IJJJJJ,JJJJJ

这是基础,请帮助我扩展:

protected void Main()
{
    char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };

    BruteForce(chars, 5);
}

private void BruteForce(char[] chars, int length)
{
    // for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
    // (when passed in length is 5)
    // TODO: Implement code...
}

阅读 270

收藏
2020-07-28

共1个答案

小编典典

这是我找到的解决方案之一。我喜欢它的紧凑性和分离性:

private static char[] characters =
    new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };

// length: The length of the string created by bruteforce
public static void PerformBruteForce(int length) {
    int charactersLength = characters.Length;
    int[] odometer = new int[length];
    long size = (long)Math.Pow(charactersLength, length);

    for (int i = 0; i < size; i++) {
        WriteBruteForce(odometer, characters);
        int position = 0;
        do {
            odometer[position] += 1;
            odometer[position] %= charactersLength;
        } while (odometer[position++] == 0 && position < length);
    }
}

private static void WriteBruteForce(int[] odometer, char[] characters) {
    // Print backwards
    for (int i = odometer.Length - 1; i >= 0; i--) {
        Console.Write(characters[odometer[i]]);
    }
    Console.WriteLine();
}
2020-07-28