我想创建一系列4个字母的所有排列的数组(对于4种类型的核苷酸碱基称为A,C,G,T)。程序应该询问用户k的值,排列的长度。我已经将它工作到可以得到排列的程度,但它只显示没有重复的那些。这是程序,它现在给我的输出,以及我希望它给我的输出。
import java.util.Arrays;
import TerminalIO.*;
public class Permute {
static KeyboardReader reader= new KeyboardReader ();
static int k= reader.readInt("Enter k-tuple");
static void permute(int level, String permuted,
boolean[] used, String original) {
if (level == k) {
System.out.println(permuted);
} else {
for (int i = 0; i < 4; i++) {
if (!used[i]) {
used[i] = true;
permute(level + 1, permuted + original.charAt(i), used, original);
used[i] = false;
}
}
}
}
public static void main(String[] args) {
String s = "ACGTACGTACGTACGTACGT";
boolean used[] = new boolean[20];
Arrays.fill(used, false);
permute(0, "", used, s);
}
}
当我输入K值为2时,它会给我:
理想情况下,它会打印:
答案 0 :(得分:1)
public class Permute {
static String s = "ACGT";
static void permute(int level, String prefix) {
if (level == 0) {
System.out.println(prefix);
return;
}
for (int i = 0; i < s.length(); i++)
permute(level - 1, prefix + s.charAt(i));
}
public static void main(String[] args) {
int k = 4;
permute(k, "");
}
}
答案 1 :(得分:1)
ArrayList<ArrayList<String>> results= new ArrayList<ArrayList<String>>();
public static void main(String... args) {
String[] letters= new String[] {"a", "t", "g", "c"};
List<String> list= Arrays.asList(letters);
for (int i=0; i<list.size(); i++) {
ArrayList<String> startList= new ArrayList<String>();
startList.add(list.get(i));
permute(list, 2, startList);
}
//result lists of strings are saved in results
for (ArrayList<String> result : results) {
System.out.println(result);
}
}
private static void permute(List<String> letters, int endLength, List<String> startList) {
if (startList.size() >= endLength) {
results.add(startList);
return;
}
for (int i=0; i<letters.size(); i++) {
ArrayList<String> newStartList= new ArrayList<String>(startList);
newStartList.add(letters.get(i));
permute(letters, 2, newStartList);
}
}
答案 2 :(得分:1)
这个怎么样? (没有递归)
void permute(char[] alphabet, int k) {
int permutationNumber = (int) Math.pow(alphabet.length, k);
for (int i = 0; i < permutationNumber; i++) {
for (int j = 0; j < k; j++) {
System.out.print(alphabet[(i + (j * i / alphabet.length)) % alphabet.length]);
}
System.out.println();
}
}