Permutation of an array, with repetition, in Java

前端 未结 4 1058
名媛妹妹
名媛妹妹 2021-01-12 01:47

There are some similar questions on the site that have been of some help, but I can\'t quite nail down this problem, so I hope this is not repetitive.

This is a home

4条回答
  •  无人共我
    2021-01-12 02:20

    I use this java realization of permutations with repetitions. A~(n,m): n = length of array, m = k. m can be greater or lesser then n.

    public class Permutations {
    
    
        static void permute(Object[] a, int k, PermuteCallback callback) {
            int n = a.length;
    
            int[] indexes = new int[k];
            int total = (int) Math.pow(n, k);
    
            Object[] snapshot = new Object[k];
            while (total-- > 0) {
                for (int i = 0; i < k; i++){
                    snapshot[i] = a[indexes[i]];
                }
                callback.handle(snapshot);
    
                for (int i = 0; i < k; i++) {
                    if (indexes[i] >= n - 1) {
                        indexes[i] = 0;
                    } else {
                        indexes[i]++;
                        break;
                    }
                }
            }
        }
    
        public static interface PermuteCallback{
            public void handle(Object[] snapshot);
        };
    
        public static void main(String[] args) {
            Object[] chars = { 'a', 'b', 'c', 'd' };
            PermuteCallback callback = new PermuteCallback() {
    
                @Override
                public void handle(Object[] snapshot) {
                    for(int i = 0; i < snapshot.length; i ++){
                        System.out.print(snapshot[i]);
                    }
                    System.out.println();
                }
            };
            permute(chars, 8, callback);
        }
    
    }
    

    Example output is

    aaaaaaaa
    baaaaaaa
    caaaaaaa
    daaaaaaa
    abaaaaaa
    bbaaaaaa
    ...
    bcffffdffffd
    ccffffdffffd
    dcffffdffffd
    affffdffffdd
    bffffdffffdd
    cffffdffffdd
    ffffdffffffffd
    

提交回复
热议问题