views:

353

answers:

3

Does anyone have Java code for generating all VARIATIONS WITH REPETITION?

There are plenty of permutation and combination examples available, and variations must be the easiest one... It feels stupid to waste time to reinvent the wheel (it must be plenty of code written for this).

An example of VARIATIONS WITH REPETITION could be like this:

(tupletSize=3, input= A, B)
AAA, AAB, ABA, BAA, ABB, BAB, BBA, BBB

Thanks!

+2  A: 
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.

Mathias
Thanks a lot!I got some errors when compiling, but the code will help for sure!
EvoMangan
You are going to run out of memory long before the stack will overflow, as long as input has two or more elements.
stubbscroll
yap you're right - I guess the 'oh god - watch out of the recursion' was faster than the thinking ;-). so in release code I guess we would not hoard char[]s :-)
Mathias
A: 

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.

Helper Method
It worked like a charm? You actually got any passwords cracked? ;)
pmr
Yeah but only the ones given for homework assignment (which were 3-4 chars long) :-)
Helper Method
+1  A: 

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);
            }
        }
    }
}
polygenelubricants
Beautiful!Thanks!!!
EvoMangan