I want to compute all possible lists of pairs you could make of a set. For instance:
input = [1, 2, 3, 4, 5, 6]
output = {[(1,2), (3,4), (5,6)],
[(2,3), (4,5), (1,6)],
[(2,4), (1,3), (5,6)],
[...], .... }
Note: this example are just some random things in the output, most is removed. I don't care about the order of the lists or the pairs within those lists.
I think there would be (n-1)(n-3)(n-5)...
possible lists of pairs. First I thought you could make all permutations of the input list. With all those permutations you could group the first with the second item and the third with fourth. But obviously that is very inefficient, because you would make n!
items in the list and you would only need (n-1)(n-3)(n-5)...
. Could some give me a hint how to do this more efficiently? Is there a known algorithm or what would the proper keywords to search with? I want to implement this in JAVA, so if you want to make use of the Collections class in JAVA no problem :)
To be more clear: the input always consist of a even number of elements so all pairs in one list together are all elements in the input.
Edit:
I have look to all answer. Now I have working code thanks for that. But I need to use it for a input with size n = 26
:(. I have not implemented everything yet, but I guess it's going to run for a while :(.
n(n-1)/
2 of those. It'll be C(n,2) * C(n-2,2)*... – Esperanzaespial(5,6)
listed twice. Is that just a mistake? – Branlen!/[2^(n/2)*(n/2)!]
different pairings, so your n! solution is not such a waste. – Shin