3
$\begingroup$

I have a number of lists (only 3 shown here)

 List1 = {{1, 2}, {1, 2, 3}, {1, 2, 3, 4, 5}};
 List2 = {{1, 2, 4, 8, 7}, {1, 2, 9, 10}};
 List3 = {{9, 11, 1}, {1, 9, 11, 13}, {1, 9, 12}, {1, 9, 14}};

I want to combine these lists in the following way: Union the last element of List1 with each element of List2, and add it to the end of List1, then Union the last element of List2 to all the elements of List3 and add them to the end of List1.

Producing

{{1, 2}, {1, 2, 3}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5, 7, 8}, {1, 2, 3, 
 4, 5, 7, 8, 9, 10}, {1, 2, 3, 4, 5, 7, 8, 9, 10, 11}, {1, 2, 3, 4, 
 5, 7, 8, 9, 10, 11, 13}, {1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 
 13}, {1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13}}

I should mention, the numbers are random, although here it appears as consecutive at some places.

Edit

With @ciao's help, I have the solution

Union@FoldList[Union, Join[List1, List2, List3]]

However, it seems to drop repeated elements as it appears in List3.

Edit 2

Fidgeting around for a bit, I realized on dropping the outer Union, the problem is solved.

FoldList[Union, Join[List1, List2, List3]]
$\endgroup$
  • 1
    $\begingroup$ You could have devised a perhaps shorter and more clear example! $\endgroup$ – Dr. belisarius Jun 26 '15 at 22:50
  • 1
    $\begingroup$ Your output does not match what you describe. r1 = Union[list1[[-1]], #] & /@ list2; r2 = Union[list2[[-1]], #] & /@ list3; r3 = {r1, r2} $\endgroup$ – Nasser Jun 26 '15 at 23:08
  • 1
    $\begingroup$ Union@FoldList[Union, Join[list1, list2, list3]] produces the output shown... but that's about as far as I'm willing to decode the OP - perhaps a clearer example/explanation is warranted? $\endgroup$ – ciao Jun 26 '15 at 23:26
  • 1
    $\begingroup$ @ciao Is there a way to modify your code so that it doesn't truncates identical elements in the list? See edited version. $\endgroup$ – HuShu Jun 27 '15 at 0:42
  • 1
    $\begingroup$ @HuShu: +1 on figuring out your question to me... $\endgroup$ – ciao Jun 27 '15 at 6:27
3
$\begingroup$

This works

   FoldList[Union, Join[List1, List2, List3]]
$\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.