Possible list combinations

I have an arraylist of objects that I want to create all possible combinations (according to a simple set of rules). Each object that is stored in the list contains a squadNumber and a string. Below is an example of a typical list that I keep:

0: 1, A
1: 1, B
2: 2, A
3: 2, B
4: 3, C
5: 3, D
6: 4, C
7: 4, D

I want to get all combinations in which each squadNumber can be present only once, for example: (1, A), (2, A), (3, C), (4, C), then the following combination (1, A) , (2, A), (3, C), (4, D). How do I do this in java? I usually use a nested loop, but the fact that it is all stored in the same list makes it difficult for me.

Thanks paintstripper

+5
source share
1 answer

EDITED

Algorithm:

  • . , 1, 2 ..
  • dfs. n- n- .

// Split squads by numbers, so we can iterate through each number independently.
private Map<Integer, List<Squad>> splitSquadsByNumbers(List<Squad> squads) {
    Map<Integer, List<Squad>> res = new HashMap<Integer, List<Squad>>();
    for (Squad squad : squads) {
        if (res.get(squad.getNumber()) == null) {
            res.put(squad.getNumber(), new ArrayList<Squad>());
        }
        res.get(squad.getNumber()).add(squad);
    }
    return res;
}

List<Integer> squadNumbers;
Map<Integer, List<Squad>> squadsByNumbers;
Stack<Squad> stack;

// Iterating through each squad with number squadNumbers[position] and try to add to stack, at the end pop it from stack.

private void dfs(int position) {
    if (position == squadNumber.size()) {
        System.out.println(stack.toString());
    } else {
        for (Squad squad : squadsByNumbers.get(squadNumber.get(position))) {
            stack.push(squad);
            dfs(position + 1);
            stack.pop();
        }
    }
}

private void main(List<Squad> squads) {
    squadsByNumbers = splitSquadsByNumbers(squads);
    squadNumber = new ArrayList(squadsByNumber.keySet());
    Collections.sort(squadNumbers);
    stack = new Stack<Squad>();
    dfs(0);
}
+3

All Articles