6

I have a list {1, 2, 3, 4} and wish to form

 {{{1,2},{3,4}}, 
 {{1,3},{2,4}}, 
 {{1,4},{2,3}}}

I ended up doing it manually like this:

a={1,2,3,4}
{{{a[[1]],a[[2]]}, {a[[3]],a[[4]]}},
{{a[[1]],a[[3]]}, {a[[2]],a[[4]]}},
{{a[[1]],a[[4]]}, {a[[2]],a[[3]]}}}

Is there a way to do this more simply? Of course this is a simplified question from the actual problem which is more complicated. An answer to this can be generalized to my actual problem. Thanks.

VLC
  • 9,818
  • 1
  • 31
  • 60
Charlie
  • 61
  • 1

2 Answers2

2

When I understood right what you try to achieve, then yes, there are some ways. Whether it still works in your real life example is another thing. Let me give two examples:

1. Method

Select[Nest[Subsets[#, {2}] &, {1, 2, 3, 4}, 2], 
 Intersection @@ # === {} &]

Here, we create first all possible subsets of length 2 of {1,2,3,4}. Then we do this step again which leaves us with elements of the form {{1, 4}, {2, 3}} but, there are cases when a number which is in the first part appears in the last part too. Therefore, we select only those elements, where the Intersection of the first and the last part is the empty set.

2. Method

Union[Map[Sort, Partition[#, 2] & /@ Permutations[{1, 2, 3, 4}], -2]]

Here, we create all permutations which will probably not work in your real case. Than we partition those permutations into the correct form. This contains the elements {{1, 2}, {3, 4}} and {{1, 2}, {4, 3}}. Therefore, we sort all first and last parts and delete the duplicates with Union.

halirutan
  • 112,764
  • 7
  • 263
  • 474
2
Needs["Combinatorica`"]
Cases[KSetPartitions[{1, 2, 3, 4}, 2], ConstantArray[{_, _}, 2]]

=>

{

{{1, 2}, {3, 4}},

{{1, 4}, {2, 3}},

{{1, 3}, {2, 4}}

}

Extending the method to a list with 6 elements:

Cases[KSetPartitions[{1, 2, 3, 4, 5, 6}, 3], ConstantArray[{_, _}, 3]]

=>

{

{{1, 2}, {3, 4}, {5, 6}}, {{1, 2}, {3, 6}, {4, 5}},

{{1, 2}, {3,5}, {4, 6}}, {{1, 4}, {2, 3}, {5, 6}},

{{1, 3}, {2, 4}, {5, 6}}, {{1, 6}, {2, 3}, {4, 5}},

{{1, 3}, {2, 6}, {4, 5}}, {{1, 5}, {2,3}, {4, 6}},

{{1, 3}, {2, 5}, {4, 6}}, {{1, 6}, {2, 5}, {3, 4}},

{{1, 5}, {2, 6}, {3, 4}}, {{1, 6}, {2, 4}, {3, 5}},

{{1,4}, {2, 6}, {3, 5}}, {{1, 5}, {2, 4}, {3, 6}},

{{1, 4}, {2, 5}, {3, 6}}

}

Edit

See Rojo's answer to this question for a much better method.

user1066
  • 17,923
  • 3
  • 31
  • 49