迭代Java中的字符数组 - 改进算法

时间:2013-03-07 11:43:41

标签: java arrays algorithm recursion char

我正在尝试遍历我的数组以生成给定char数组的所有可能组合。

如果我指定的长度是4,那么我希望它迭代遍历数组中字符的所有组合,长度为4.

它看起来像这样:

char[] charArray = "abcdefghijklmnopqrstuvwxyz".toCharArray();

我想要的方法输出:

一个, b, C, ... X, Y, Z, AA, AB, AC, ... 斧头, 唉, AZ, BA, BB, 公元前, ... BX, 通过, BZ, CA, CB, CC, ... zzzx, zzzy, ZZZZ

以下是一些代码:

cs = charArray;
cg = new char[4]; // 4 up to 4 characters to guess

int indexOfCharset = 0; // should I be using all these?
int indexOfCurrentGuess = 0;
int positionInString = 0;

public void incrementNew() {
    // 1 DIGIT guesses
    if (cg.length == 0) {
        if (indexOfCharset == cs.length) {
            cg = new char[cg.length + 1];
        } else {
            cg[positionInString] = nextChar();
        }
    }
    // 2 DIGIT guesses
    else if (cg.length == 1) {
        if (cg[0] == cs.length && cg[1] == cs.length) {
            cg = new char[cg.length + 1];
        } else {
            ... Something goes here <-
            cg[positionInString] = nextChar();
        }
    }
    System.out.println("cg[0]=" + cg[0]);
}

public char nextChar() {
    char nextChar;
    if (indexOfCharset < cs.length) {
        nextChar = cs[indexOfCharset];
    } else {
        indexOfCharset = 0;
        nextChar = cs[indexOfCharset];
    }
    indexOfCharset++;
    //System.out.println("nextChar = " + nextChar);
    return nextChar;

}

我能想到的唯一方法就是使用大量的IF语句 - 是否有算法或方法来做它更整洁?如果没有,那么有关如何处理两个或更多字符的任何建议?

编辑:

我希望它适用于任何未分类的char数组,而不仅仅是a-z。

我发现的所有实现仅适用于排序数组..

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

static char[] letters = "abcdefghijklmnopqrstuvwxyz".toCharArray();

static void getChars(char[] lastChars, int pos, int length) {
    for (char c : letters) {
        char[] newChars = lastChars.clone();
        newChars[pos] = c; // if you have "aa" for example and the current length is 4. If c = "a", newChars is now "aaa"
        if (pos + 1 < length) { // as your lenths is 4 and you still have only 3 letters, getChars adds the missing ones
            getChars(newChars, pos + 1, length);
        } else {
            System.out.println(newChars);
        }
    }
}

public static void main(String[] args) {
    int maxLength = 4;

    for (int length = 1; length <= maxLength; length++) {
        for (char c : letters) {
            if (length > 1) {
                char[] chars = new char[length];
                chars[0] = c;
                getChars(chars, 1, length);
            } else {
                System.out.println(c);
            }
        }
    }

}