简体   繁体   中英

java list generator of all possible combinations

I want to make a function that will make a list of all possible combinations of a charset between length n and n+m in java. I'm trying to demonstrate how hash cracking works and I was asked to write in java, but I'm not very familiar with it. I would also like to know if there is something like the python yeald function in java and if so how can I imlement it.

Please try if this sample can help you. It takes 3 variables: The charset, the max and the min length and lists all combinations.

import java.util.Arrays;

public abstract class Main {
    int max = 4;
    int min = 2;

    public static void main(String args[]) {
        new Main() {
            public void element(char[] result, int offset, int length) {
                System.out.println(new String(result, offset, length));
            }
        }.generate("ABCD");
    }

    private void generate(char[] input) {
        char[] result = new char[input.length];
        int[] index = new int[input.length];

        // initialize the arrays.
        Arrays.fill(result, 0, result.length, input[0]);
        Arrays.fill(index, 0, index.length, 0);

        // loop over the output lengths.

        for (int length = min; length <= max; length++) {
            int updateIndex = 0;
            do {
                element(result, 0, length);

                // update values that need to reset.
                for (updateIndex = length - 1;
                     updateIndex != -1 && ++index[updateIndex] == input.length;
                     result[updateIndex] = input[0], index[updateIndex] = 0, updateIndex--)
                    ;

                // update the character that is not resetting, if valid
                if (updateIndex != -1) result[updateIndex] = input[index[updateIndex]];
            }
            while (updateIndex != -1);
        }
    }

    void generate(String input) {
        generate(input.toCharArray());
    }

    public abstract void element(char[] result, int offset, int length);
}

Test

AA
AB
AC
AD
BA
BB
BC
BD
CA
CB
CC
CD
DA
DB
DC
DD
AAA
AAB
AAC
AAD
ABA
ABB
ABC
ABD
ACA
ACB
ACC
ACD
ADA
ADB
ADC
ADD
BAA
BAB
BAC
BAD
BBA
BBB
BBC
BBD
BCA
BCB
BCC
BCD
BDA
BDB
BDC
BDD
CAA
CAB
CAC
CAD
CBA
CBB
CBC
CBD
CCA
CCB
CCC
CCD
CDA
CDB
CDC
CDD
DAA
DAB
DAC
DAD
DBA
DBB
DBC
DBD
DCA
DCB
DCC
DCD
DDA
DDB
DDC
DDD
AAAA
AAAB
AAAC
AAAD
AABA
AABB
AABC
AABD
AACA
AACB
AACC
AACD...

You can try it online .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM