0

So, I'm trying to generate all the permutations for a list of numbers in an ArrayList, and then add every single one to a hashmap, giving each permutation an ID. Like in the image below, the apple would be the final permutation which would have an ID inside the map.

Like in this image: https://i.stack.imgur.com/3K68U.png

Here is what I have tried so far, I'm having trouble with the swapping part, I get tangled and lost.

HashMap<String, Long> permutationAndID = new HashMap<>();
for(long i = 1; i <= maxTriplets; i++) {
    /*
     * GENERATE PERMUTATIONS
     * AND ADD TO HASHMAP
     */
    for(int j = 0; j <= inputs.size()-1; j++) {
        String val1 = String.valueOf(inputs.get(j));
        for(int k = 0; k <= inputs.size()-1; k++) {
            String val2 = String.valueOf(inputs.get(k));
            while(val2 == val1) {
                k = k+1;
                val2 = String.valueOf(inputs.get(k));
            }
            for(int l = 0; l <= inputs.size()-1; l++) {
                String val3 = String.valueOf(inputs.get(l));
                while(val3 == val1 & val3 == val2) {
                    l = l+1;
                    val3 = String.valueOf(inputs.get(l));
                }
                String permutation = val1 + "," + val2 + "," + val3;
                System.out.println("Permutation: [" + permutation + "] ID: " + i);
                permutationAndID.put(permutation, i);
            }                   
        }
    }
}
if(permutationAndID.size() == maxTriplets) {
    System.out.println("\nAll " + maxTriplets + " permutations generated correctly!");
}else {
    System.out.println("\nAn error occured while generating the permutations!");
}

With 3 entry values I get 162 permutations, when there should only be 6.

João Dias
  • 16,277
  • 6
  • 33
  • 45
  • I forgot to add that maxTriplets is this: long maxTriplets = factorial(inputs.size())/factorial(inputs.size()-3); where inputs is the ArrayList with integers in it. – Jorge Ramirez Nov 14 '21 at 23:08
  • I suggest, as an initial change, you read the accepted answer in https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java/513839#513839 and alter your code to account for that. – sprinter Nov 14 '21 at 23:41

0 Answers0