好吧,我陷入了如何使用指定字符生成具有所有可能值的字符串的问题。好吧,我不知道怎么解释好,这里举个例子:
字符:a, b, c
一代:
abc
aab
abb
acc
baa
bbb
bbc
bac
cab
ccc
aaa
cbb
caa
ccb
cca
bab
bcb
我试过使用一个字符列表,然后迭代这个列表中的每个字符,然后再次迭代列表中的每个字符,但是......假设它不起作用。
我自己对这个问题的回答的副本:
这将适用于a,b,c
或任何其他连续的字符序列:
import java.util.Arrays;
import java.util.Iterator;
public class BruteForceIterator implements Iterator<String> {
private char min, max;
private char[] current;
private char[] last;
private int reachedLast = 0;
public BruteForceIterator(char min, char max, int length) {
this.min = min;
this.max = max;
current = new char[length];
Arrays.fill(current, min);
last = new char[length];
Arrays.fill(last, max);
}
@Override
public boolean hasNext() {
return reachedLast < 2;
}
@Override
public String next() {
String str = new String(current);
for(int i = current.length - 1; i >= 0; i--) {
char next = following(current[i]);
current[i] = next;
if (next != min) {
break;
}
}
if (Arrays.equals(current, last) || reachedLast > 0) {
reachedLast++;
}
return str;
}
private char following(char in) {
if (in < max) {
return (char) (in + 1);
} else {
return min;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("No with me, sir!");
}
public static void main(String[] args) {
BruteForceIterator bit = new BruteForceIterator('a', 'c', 3);
while (bit.hasNext()) {
System.out.println(bit.next());
}
}
}
我很快在下面制作了这段代码。您可能需要对其进行一些编辑才能使其工作或适应您的需求我只是想与您分享我的代码的想法。但是我会推荐 jlordo 的答案,因为它更有效。
Array String[] = new Array[]{"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"}
ArrayList<String> numbersrandom;
for(int a = 0; i <= 26; i++){
for(int b = 0; i <= 26; i++){
for(int c = 0; i <= 26; i++){
numbersrandom.add(String[a]+String[b]+String[c]);
}
}
}
使用此代码后,您可以使用随机生成器和 for 循环来随机混合这些。祝你好运!