Get all 1-k tuples in a n-tuple

前端 未结 3 1073
借酒劲吻你
借酒劲吻你 2021-01-29 04:38

With n=5 and k=3 the following loop will do it

List l=new ArrayList();
l.add(\"A\");l.add(\"B\");l.add(\"C\");l.add(\"D\");l.add(\"E\         


        
3条回答
  •  逝去的感伤
    2021-01-29 05:26

    Apache commons has iterators for subsets of size k, and for permutations. Here is an iterator that iterates through 1-k tuples of an n-tuple, that combines the two:

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    
    import org.apache.commons.collections4.iterators.PermutationIterator;
    import org.apache.commons.math3.util.Combinations;
    
    public class AllTuplesUpToKIterator implements Iterator> {
        private Iterator combinationIterator;
        private PermutationIterator permutationIterator;
        int i;
        int k;
        int n;
    
        public AllTuplesUpToKIterator(int n, int k) {
            this.i = 1;
            this.k = k;
            this.n = n;
            combinationIterator = new Combinations(n, 1).iterator();
            permutationIterator = new PermutationIterator(intArrayToIntegerList(combinationIterator.next()));
        }
    
        @Override
        public boolean hasNext() {
            if (permutationIterator.hasNext()) {
                return true;
            } else if (combinationIterator.hasNext()) {
                return true;
            } else if (i next() {
            if (!permutationIterator.hasNext()) {
                if (!combinationIterator.hasNext()) {
                    i++;
                    combinationIterator = new Combinations(n, i).iterator();
                }
                permutationIterator = new PermutationIterator(intArrayToIntegerList(combinationIterator.next()));          
            }
            return permutationIterator.next();
        }
    
        @Override
        public void remove() {
            // TODO Auto-generated method stub
    
        }
    
        public static List intArrayToIntegerList(int[] arr) {
            List result = new ArrayList();
            for (int i=0; i< arr.length; i++) {
                result.add(arr[i]);
            }
            return result;
        }
    
    
        public static void main(String[] args) {
            int n = 4;
            int k = 2;
            for (AllTuplesUpToKIterator iter= new AllTuplesUpToKIterator(n, k); iter.hasNext();) {
                System.out.println(iter.next());
            }
    
        }
    }
    

提交回复
热议问题