我正在编写一个程序来列出字母 A、B、C 和 D 的所有可能组合。我已经成功编写了一个程序来列出所有可能的排列。
但是,我将如何重写程序来工作并产生所有组合(即:ABCD = DCBA 和 AB = BA,因此只要有一个存在,就不需要列出另一个)。
到目前为止,我当前程序的代码是:
import java.util.ArrayList;
public class Perms {
public static void main(String[] args) {
ArrayList<Character> characters = new ArrayList<Character>();
characters.add('A');
characters.add('B');
characters.add('C');
characters.add('D');
int count = 0;
for (int i = 0; i < characters.size(); i++) {
for (int j = 0; j < characters.size(); j++) {
for (int k = 0; k < characters.size(); k++) {
for (int d = 0; d < characters.size(); d++) {
count++;
System.out.println(count + ": " + characters.get(i) + characters.get(j) + characters.get(k) + characters.get(d));
}
}
}
}
}
}
最佳答案
你的第二种情况相当于4位二进制值的列表。假设 A 是最右边的数字,D 是最左边的数字。那么一共有16种组合:
DCBA
0000
0001
0010
0011
0100
...
1110
1111
每个组合的解码如下:
DCBA
1010 = DB
因为 B 和 D 位置都有。
您可以使用多种方法在 Java 中生成和/或解码二进制数。
例如,按位运算:
public static void main(String[] args) {
// starting from 1 since 0000 is not needed
for(int i=1; i<16; ++i) {
// bitwise operation & detects 1 in given position,
// positions are determined by sa called "masks"
// mask has 1 in position you wish to extract
// masks are 0001=1, 0010=2, 0100=4 and 1000=8
if( (i & 1) > 0 ) System.out.print("A");
if( (i & 2) > 0 ) System.out.print("B");
if( (i & 4) > 0 ) System.out.print("C");
if( (i & 8) > 0 ) System.out.print("D");
System.out.println("");
}
}
关于Java - 列表组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249581/