Aut*_*Eta 9 java algorithm logic
我想用az创建所有可能的5个字母单词.请建议任何好的和快速的算法.
我试过创建一个,它看起来像这样......
byte[] allchar=new byte[] {'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'};
int lengthOfAllChar=allchar.length;
System.out.println(lengthOfAllChar);
for (int i = 0; i < lengthOfAllChar; i++){
for(int j = 0; i < lengthOfAllChar; j++){
StringBuffer finalWordBuffer = new StringBuffer();
finalWordBuffer.append((char)allchar[i]);
finalWordBuffer.append((char)allchar[j]);
}
}
Run Code Online (Sandbox Code Playgroud)
Whi*_*g34 24
以下是为任意长度的任何字符集生成所有序列的示例:
public class WordPermutations {
public static void main(String[] args) {
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
int len = 5;
iterate(chars, len, new char[len], 0);
}
public static void iterate(char[] chars, int len, char[] build, int pos) {
if (pos == len) {
String word = new String(build);
// do what you need with each word here
return;
}
for (int i = 0; i < chars.length; i++) {
build[pos] = chars[i];
iterate(chars, len, build, pos + 1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的机器上花费大约250ms来迭代所有11,881,376个序列.
请注意,new char[len]仅在开头创建一次,并重新用作构建排列的构建.第一次调用iterate()开始用pos的0.跳到for循环,循环遍历每个字符.构建的第一个char设置为,然后我们递归调用相同的方法来设置下一个pos + 1.一旦这发生了5次pos将会在len.这是在pos == len方法顶部开始的时候.然后它只是构建一个String构建在构建中的东西,并且有你的话.
这也可以轻松完成而无需递归(此处为 C)
int i, k, n;
char tmp[6]; tmp[5] = 0;
for (i=0;i<26*26*26*26*26;i++) {
n = i;
for (k=4;k>=0;k--){
tmp[k] = 'a' + (n % 26);
n /= 26;
}
output_string(tmp);
}
Run Code Online (Sandbox Code Playgroud)
或者你可以用carry来做:
char tmp[6]; int i, k;
strcpy(tmp, "aaaaa");
for (i=0;i<26*26*26*26*26;i++) {
output_string(tmp);
tmp[4]++;
k = 4;
while (k > 0 && tmp[k] == 'z') { tmp[k] = 'a'; k--; tmp[k]++; }
}
Run Code Online (Sandbox Code Playgroud)