创建4个字母的所有排列
问题描述:
我想创建一个由一系列4个字母组成的所有排列的数组(将4种核苷酸碱基称为A,C,G,T).程序应询问用户k的值,即排列的长度.我已经将其工作到可以得到排列的程度,但是它只显示没有重复的排列.这是程序,它现在给我的输出,以及我希望它给我的输出.
I want to create an array of all permutations of a series of 4 letters (Call them A,C,G,T for the 4 types of nucleotide bases). The program should ask the user for the value of k, the length of the permutation. I've got it working to the point where I can get the permutations, but it only shows the ones with no repeats. Here's the program, the output it's giving me right now, and the output I want it to give me.
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);
}
}
当我输入2的K值时,它会给我:
When I enter a K value of 2,it gives me:
- AC
- AG
- AT
- CA
- CG
- CT
- GA
- GC
- GT
- TA
- TC
- TG
- AC
- AG
- AT
- CA
- CG
- CT
- GA
- GC
- GT
- TA
- TC
- TG
理想情况下,它将打印:
Ideally, it would print:
- AC
- AG
- AT
- AA
- CA
- CC
- CG
- CT
- GA
- GG
- GC
- GT
- TA
- TC
- TG
- TT
- AC
- AG
- AT
- AA
- CA
- CC
- CG
- CT
- GA
- GG
- GC
- GT
- TA
- TC
- TG
- TT
答
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, "");
}
}