Java - 列表组合

min*_*ino 0 java combinations for-loop arraylist

我正在编写一个程序来列出字母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));
                    }
                }
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Suz*_*ioc 5

您的第二种情况相当于4位二进制值列表.我们假设A是最右边的数字,D是最左边的数字.然后共有16种组合:

DCBA
0000
0001
0010
0011
0100
...
1110
1111
Run Code Online (Sandbox Code Playgroud)

每个组合解码如下:

DCBA
1010 = DB
Run Code Online (Sandbox Code Playgroud)

因为在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("");

    }
}
Run Code Online (Sandbox Code Playgroud)