Conditional permutation of combining multiple lists

We have a list of lists. The function listNumbersToElements here takes such a list, along with a set of indices into it. For each index, it takes the next element from the correct list.

ClearAll[listNumbersToElements];
listNumbersToElements[inds_List, allLists_List] := Block[{c},
  c[_] = 0;
  Function[{listIndex},
    ++c[listIndex]; allLists[[listIndex, c[listIndex]]]] /@ inds]

Example:

In[157]:= listNumbersToElements[{1, 2, 1, 2}, {{1, 2}, {a, b}}]
listNumbersToElements[{1, 1, 2}, {{1, 2}, {a, b}}]
listNumbersToElements[{2, 2, 1, 1}, {{1, 2}, {a, b}}]


Out[157]= {1, a, 2, b}

Out[158]= {1, 2, a}

Out[159]= {a, b, 1, 2}

This function takes the list of lists, fills a list with n copies of each list's index, where n is the length of the respective list, then creates all permutations of the list of indices. Then it applies listNumbersToElements to each permutation, getting the final result as desired.

ClearAll[conditionalPermutation];
conditionalPermutation[lists__List] := 
 Module[{argsAsList = List@lists},
  listNumbersToElements[#, argsAsList] & /@ Permutations[Flatten[
     MapIndexed[Table[First[#2], Length[#1]] &, argsAsList],
     1]]]

Examples:

In[161]:= conditionalPermutation[{1, 2}, {a, b}]
conditionalPermutation[{1, 2}, {a, b, c}]

Out[161]= {{1, 2, a, b}, {1, a, 2, b}, {1, a, b, 2}, {a, 1, 2, b}, {a,
   1, b, 2}, {a, b, 1, 2}}

Out[162]= {{1, 2, a, b, c}, {1, a, 2, b, c}, {1, a, b, 2, c}, {1, a, 
  b, c, 2}, {a, 1, 2, b, c}, {a, 1, b, 2, c}, {a, 1, b, c, 2}, {a, b, 
  1, 2, c}, {a, b, 1, c, 2}, {a, b, c, 1, 2}}

This is an extended comment in that it gives (I hope) the number of arrangements rather than the arrangements. However, I think the steps here will suggest a way to obtain the arrangements:

a = {a1, a2};
b = {b1, b2, b3, b4};
na = Length[a];
nb = Length[b];
ip = IntegerPartitions[nb, Min[na + 1, nb]]
(* {{4},{3,1},{2,2},{2,1,1}} *)
Sum[Binomial[na + 1, Length[ip[[i]]]] Length[Permutations[ip[[i]]] ], {i, Length[ip]}]
(* 15 *)

The logic is that there will be na+1 places to put the numbers from b:

  x  a1  x  a2  x

For this example there are 3 places (na+1) to put items from b. So we look at all of the Min[na+1,nb] integer partitions of b and weight those by the number of associated permutations.