6
$\begingroup$

Suppose that I have a list of numbers

list = {{{1, 0}, {-1, 1}, {0, -1}}, {{-1, 0, 1}, {-1, 1, -1}, {-1, -1, 0}, {1, 1, 0}, {1, -1, 1}, {1, 0, -1}}}

I would like to Join each element of the first sublist with each element of the second list. In principle I would like to do it recursively, so the list might have also multiple sublists. The final result should be

final = {
{{1,0,-1, 0, 1}, {1,0,-1, 1, -1}, {1,0,-1, -1, 0}, {1,0,1, 1, 0}, {1,0,1, -1, 1}, {1,0,1, 0, -1}}, (*first union*)
{{-1, 1,-1, 0, 1}, {-1, 1,-1, 1, -1}, {-1, 1,-1, -1, 0}, {-1, 1,1, 1, 0}, {-1, 1,1, -1, 1}, {-1, 1,1, 0, -1}},  (*second union*)
{{0, -1,-1, 0, 1}, {0, -1,-1, 1, -1}, {0, -1,-1, -1, 0}, {0, -1,1, 1, 0}, {0, -1,1, -1, 1}, {0, -1,1, 0, -1}}  (*third union*)
}

In case I had three sublist, I need to create all possible combination of these final result (which can be flattened) with the element of the third sublist. So I was thinking of sum recursive solution that applies to each pair of the array.

What is the correct way of doing it in Mathematica?

EDIT with example:

Just to give you a case with three vectors: list ={{{1}},{{1,0},{-1,1},{0,-1}},{{-1,0,1},{-1,1,-1},{-1,-1,0},{1,1,0},{1,-1,1},{1,0,-1}}},

I made a loop like:

temp={};
Do[
temp=AppendTo[temp,Join[list[[1,i]],list[[2,j]],list[[3,k]]]];
,{i,1,Length[list[[1]]]},{j,1,Length[list[[2]]]},{k,1,Length[list[[3]]]}]

and it does the job, but of course, I could have a list with more than three sublists, and for sure there is a better way than a Do loop. But now it is clear what I want, I guess.

$\endgroup$

2 Answers 2

8
$\begingroup$

You can get the desired ouput like so:

Join@Outer[Join, list[[1]], list[[2]], 1]

and check

final - Join@Outer[Join, list[[1]], list[[2]], 1]

test

$\endgroup$
2
  • 3
    $\begingroup$ Perfect, I can use your function Join@Outer[Join, Evaluate @@ list, 1] for a generic long list and it works. I then flatten as much time as I need. Thanks! $\endgroup$ Commented Mar 22, 2022 at 21:27
  • 1
    $\begingroup$ @AlessandroMininno hi. Yes, indeed this is the idea. You can pass as many lists as you want. You might want to have a look at Outer, but it seems you got the general picture $\endgroup$
    – bmf
    Commented Mar 22, 2022 at 21:28
0
$\begingroup$

1st solution

{x, y} = list;

la = (n |-> Join[x[[n]], #] & /@ y) /@ Range[Length @ x];

2nd solution

lb =
  GatherBy[
    Cases[Subsets[Join @@ list, {2}], x : {{_, _}, {_, _, _}} :> Flatten[x]],
  First];

Test

la == lb == final

True

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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