Code for Variations with repetition (combinatorics)?

后端 未结 4 1568
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 02:34

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

There are plenty of permutation and combination examples available, and variations must be

4条回答
  •  一生所求
    2020-12-15 03:22

    public class Main {
    
        public static void main(String[] args) throws IOException {
            LinkedList items = new LinkedList();
            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 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.

提交回复
热议问题