どうぞ。再帰的な方法で、ワイルドカードの位置に制約はありません。置換文字を選択できます ("01"
たとえば、バイナリ カウント、または"0123456789"
すべての自然文字)。
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String input = "base 3 : **"; // the input, with wildcard
String replacable = "*"; // wildcard char
String replacedBy = "0123"; // all the possibilities for wildcard replacement
ArrayList<String> output = genCombinations(input, replacable, replacedBy);
// just print the results
for(String s : output)
System.out.println(s);
}
private static ArrayList<String> genCombinations(String input,String replacable, String replacement) {
StringBuilder sb = new StringBuilder(input);
ArrayList<String> out = new ArrayList<>(); //may warn with jdk < 1.7
// find the first wildcard
int index = input.indexOf(replacable);
if(index==-1){
//no wildcard found
out.add(sb.toString());
return out;
}
for(int i = 0; i<replacement.length(); ++i){
char c = replacement.charAt(i);
sb.setCharAt(index, c);
// gen all combination with the first wildcard already replaced
out.addAll(genCombinations(sb.toString(),replacable, replacement));
}
return out;
}
}
出力:
base 3 : 00
base 3 : 01
base 3 : 02
base 3 : 03
base 3 : 10
base 3 : 11
base 3 : 12
base 3 : 13
base 3 : 20
base 3 : 21
base 3 : 22
base 3 : 23
base 3 : 30
base 3 : 31
base 3 : 32
base 3 : 33