Java - Permutation of ArrayList elements (Integer) - Can't get it to work properly

后端 未结 2 623
说谎
说谎 2020-12-19 19:05

I\'ve been looking around quite a bit to solve my issue. I got many problems solved but this one is still haunting me :S It\'s been a long time I haven\'t touch Java program

相关标签:
2条回答
  • 2020-12-19 19:43

    Try this, it seems to work, it uses recursion.

    public class Permute {
    
        public static List<List<Integer>> permute(Integer...myInts){
    
            if(myInts.length==1){
                List<Integer> arrayList = new ArrayList<Integer>();
                arrayList.add(myInts[0]);
                List<List<Integer> > listOfList = new ArrayList<List<Integer>>();
                listOfList.add(arrayList);
                return listOfList;
            }
    
            Set<Integer> setOf = new HashSet<Integer>(Arrays.asList(myInts));   
    
            List<List<Integer>> listOfLists = new ArrayList<List<Integer>>();
    
            for(Integer i: myInts){
                ArrayList<Integer> arrayList = new ArrayList<Integer>();
                arrayList.add(i);
    
                Set<Integer> setOfCopied = new HashSet<Integer>();
                setOfCopied.addAll(setOf);
                setOfCopied.remove(i);
    
                Integer[] isttt = new Integer[setOfCopied.size()];
                setOfCopied.toArray(isttt);
    
                List<List<Integer>> permute = permute(isttt);
                Iterator<List<Integer>> iterator = permute.iterator();
                while (iterator.hasNext()) {
                    List<java.lang.Integer> list = iterator.next();
                    list.add(i);
                    listOfLists.add(list);
                }
            }   
    
            return listOfLists;
        }
    
        public static void main(String[] args) {
            List<List<Integer>> permute = permute(1,2,3,4);
            System.out.println(permute);
        }
    
    }
    

    If you don't like the List> you can easily change from arrays to list using the methods from list and static methods from java.util.Collections and java.util.Arrays.

    0 讨论(0)
  • 2020-12-19 19:49

    You can try Recursion to solve this issue:

    public static void printPermutations(int[] n, int[] Nr, int idx) {
        if (idx == n.length) {  //stop condition for the recursion [base clause]
            System.out.println(Arrays.toString(n));
            return;
        }
        for (int i = 0; i <= Nr[idx]; i++) { 
            n[idx] = i;
            printPermutations(n, Nr, idx+1); //recursive invokation, for next elements
        }
    }
    

    More info can be had from this link: Combinatorics: generate all “states” - array combinations

    You can replicate the same logic here as well.

    0 讨论(0)
提交回复
热议问题