I would like to compute all "nested permutations" (not sure if it's the right term) of a list consisting of simple elements (numbers, strings) and simple sublists (level 1 lists of simple elements).
For example, with the list {1, {2, 3}}
, I calculate the nested permutations like this:
list = {1, {2, 3}};
Flatten[# /. ({a___, b_List, c___} :> ({a, #, c} & /@ b)) & /@
Permutations[list], 1]
{1,2} {1,3} {2,1} {3,1}
As you can see, I want all possible permutations where only one of the elements in the simple sublists is included. However, my method fails if the list contains more than one simple sublist:
list2 = {1, {2, 3}, {4}}
Flatten[# /. ({a___, b_List, c___} :> ({a, #, c} & /@ b)) & /@
Permutations[list2], 1]
{1,2,{4}} {1,3,{4}} {1,4,{2,3}} {2,1,{4}} {3,1,{4}} {2,{4},1} {3,{4},1} {4,1,{2,3}} {4,{2,3},1}
I tried replacing ReplaceAll
(/.
) with ReplaceRepeated
(//.
), this however caused an infinite recursion:
ReplaceRepeated::rrlim: Exiting after {1,{2,3},{4}} scanned 65536 times. >>
How can I compute all possible permutations where only one element from each of the simple sublists is included?
Edit: there can be any number of simple elements and simple lists in a list, but there will never be any duplicates.