Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

java - Get all possible combinations of characters in an array

I have an array of characters c[][] with different mappings to each index. For example:

{'a', 'b', 'c', 'd', 'e', 'f' } {'g', 'h', 'i' }

I need to return all the possible character combinations for this array as a string. That meaning, for the above character array, I should return: "ag", "ah", "ai", "bg", "bh", "bi", "cg", "ch", "ci", etc. It would be easy to do this for a character array of only two things like above, but if there are more arrays, then I do not know what to do... Which is what I am asking you all to help me with! :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For two arrays two nested loops should do:

for (int i = 0 ; i != c[0].length ; i++) {
    for (int j = 0 ; j != c[1].length ; j++) {
        System.out.writeln(""+c[0][i]+c[1][j]);
    }
}

For more nesting you would need a recursive or an equivalent stack-based solution.

void combos(int pos, char[][] c, String soFar) {
    if (pos == c.length) {
         System.out.writeln(soFar);
         return;
    }
    for (int i = 0 ; i != c[pos].length ; i++) {
        combos(pos+1, c, soFar + c[pos][i]);
    }
}

Call this recursive function from your main() like this:

combos(0, c, "");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...