Code for Variations with repetition (combinatorics)?

倖福魔咒の 提交于 2019-11-28 22:10:59

This works as is, and it's the easiest for you to study.

public class Main {
    public static void main(String args[]) {
        brute("AB", 3, new StringBuffer());
    }
    static void brute(String input, int depth, StringBuffer output) {
        if (depth == 0) {
            System.out.println(output);
        } else {
            for (int i = 0; i < input.length(); i++) {
                output.append(input.charAt(i));
                brute(input, depth - 1, output);
                output.deleteCharAt(output.length() - 1);
            }
        }
    }
}
public class Main {

    public static void main(String[] args) throws IOException {
        LinkedList<char[]> items = new LinkedList<char[]>();
        char[] item = new char[3];
        char[] input = {'A', 'B'};
        rep(items, input, item, 0);


        for (char[] rep : items) {
            System.out.println(rep);
        }
    }

    private static void rep(LinkedList<char[]> reps, char[] input, char[] item, int count){
        if (count < item.length){
            for (int i = 0; i < input.length; i++) {
                item[count] = input[i];
                rep(reps, input, item, count+1);
            }
        }else{
            reps.add(item.clone());
        }
    }

}

produces following output: AAA AAB ABA ABB BAA BAB BBA BBB

watch out for stack overflows with big tupleSize. recursive algorithms (like this one) are usually slower than iterative versions but they are very handy to code.

How to write a brute-force password cracker

While this is no Java implementation, the part doing the permutations should be quite easy to port in Java.

I ported it to C with no knowledge of Python, and it worked like a charm.

You can use the principle of n-ary Gray code

http://en.wikipedia.org/wiki/Gray_code#Constructing_an_n-bit_Gray_code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!