5
$\begingroup$

I've got a certain class of lists with, say, 4 elements, that are lists themselves. E.g. {{1, 2, 3}, {4}, {5, 6}, {7}}. I'd like to find a way to generate a list that contains all of the cousins of this list where the sublists are permuted in all possible ways. With the previous example, this list would have size $3!\times 2!=12$.

To be really definite, in the simpler case of {{1, 2},{3,4}}, I'd want to obtain {{{1, 2},{3,4}},{{2,1},{3,4}},{{1, 2},{4,3}},{{2,1},{4,3}}}.

I feel like there should be a one line code for this but I couldn't figure it out.

Permutations/@{{1, 2, 3}, {4}, {5, 6}, {7}} returns a reasonably interesting list, out of which I'm unable to extract what I want in a simple (i.e. Mathematica) way. Using further Pick starts to demand that I get more explicitly certain lists or binary trees or so...

$\endgroup$
  • 3
    $\begingroup$ Does Tuples[Permutations /@ {{1, 2, 3}, {4}, {5, 6}, {7}}] suit your needs? $\endgroup$ – J. M. is in limbo Mar 31 '16 at 17:28
  • 4
    $\begingroup$ @J.M. Oh... Tuples is so much simpler than Outer for this... If you post that as an answer, I'll delete mine. $\endgroup$ – Martin Ender Mar 31 '16 at 17:31
  • $\begingroup$ It's not too late to edit your answer, @Martin. ;) $\endgroup$ – J. M. is in limbo Mar 31 '16 at 17:32
  • $\begingroup$ @J.M. Yes it does ! Please put this as an answer. I also like very much the explanation with Outer below. $\endgroup$ – picop Mar 31 '16 at 17:33
  • $\begingroup$ @Martin Büttner well it is simpler yes but I'm also happy that I learned about Outer today as well ! $\endgroup$ – picop Mar 31 '16 at 17:34
7
$\begingroup$

What you're looking for is the outer product of all the lists returned by Permutations /@ .... You can use Outer for that. The only issue is that Outer returns the result as a nested list (basically an n-dimensional table of all the possible permutations), so you'll have to flatten it afterwards:

lists = {{1, 2, 3}, {4}, {5, 6}, {7}};
Flatten[Outer[List, ##, 1] & @@ Permutations /@ lists, Length@lists - 1]

(* {{{1, 2, 3}, {4}, {5, 6}, {7}}, {{1, 2, 3}, {4}, {6, 5}, {7}}, 
    {{1, 3, 2}, {4}, {5, 6}, {7}}, {{1, 3, 2}, {4}, {6, 5}, {7}}, 
    {{2, 1, 3}, {4}, {5, 6}, {7}}, {{2, 1, 3}, {4}, {6, 5}, {7}}, 
    {{2, 3, 1}, {4}, {5, 6}, {7}}, {{2, 3, 1}, {4}, {6, 5}, {7}}, 
    {{3, 1, 2}, {4}, {5, 6}, {7}}, {{3, 1, 2}, {4}, {6, 5}, {7}}, 
    {{3, 2, 1}, {4}, {5, 6}, {7}}, {{3, 2, 1}, {4}, {6, 5}, {7}}} *)

Well if this is now the accepted answer, I might as well edit in J. M.'s solution for completeness. The above is essentially a manual reimplementation of the built-in Tuples so that's all you need:

Tuples[Permutations /@ lists]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.