# Selecting elements satisfying a condition

I have a list of lists(of lists):

{{{1}, {2}, {1, 2, 3}}, {{1}, {3}, {1, 2, 3}}, {{1}, {1, 2}, {1,2,
3}}, {{1}, {2, 3}, {1, 2, 3}}, {{2}, {3}, {1, 2, 3}}, {{2}, {1,
2}, {1, 2, 3}}, {{2}, {2, 3}, {1, 2, 3}}, {{3}, {1, 2}, {1, 2,
3}}, {{3}, {2, 3}, {1, 2, 3}}, {{1, 2}, {2, 3}, {1, 2, 3}}}

From the list above I want to select those lists in which two consecutive elements share either a first element or last element. It also counts if the first element of the list shares the first entry with the second element of that list, but the second element shares the last entry with the third element, etc. So from the list above I would get:

{{1},{1,2},{1,2,3}},{{2},{1,2},{1,2,3}},{{2},{2,3},{1,2,3}},{{3},{2,3},{1,2,3}}

So I did the following:test4 = Table[Select[test3,First[#[[i+1]]]==First[#[[i]]] \[Or] Last[#[[i+1]]]==Last[#[[i]]] &],{i,n-1}]

where test3 is my list of lists from above and n is the maximum length that the element in one of the list of lists can have, so in our case it is 3 and that number is known in advance. Unforunately the above doesn't work. It spits out more elements then there are in the initial list. I think it picks the elements which satify that condition for at least one pair of consecutive elements, which is not what I'm after. I'd really appreciate some help with this. Thanks!

When I'm stuck with a problem like that, I always try to decompose it into simple, testable functions, that I can understand more or less at one glance.

The first thing you want is to check if two lists share the first or last element:

shareFirstOrLast[{a_, b_}] :=
First[a] == First[b] || Last[a] == Last[b]

Then you want to extend that to more than two elements:

shareFirstOrLast[{a_, b_, rest__}] :=
shareFirstOrLast[{a, b}] && shareFirstOrLast[{b, rest}]

(this recursion will essentially call shareFirstOrLast[{a_, b_}] on every consecutive pair of elements.)

Finally, test that function on different samples and edge cases. If it fits your needs, use it with select:

Select[test3, shareFirstOrLast]

{{{1}, {1, 2}, {1, 2, 3}}, {{2}, {1, 2}, {1, 2, 3}}, {{2}, {2, 3}, {1, 2, 3}}, {{3}, {2, 3}, {1, 2, 3}}}

• Brilliant, thank you so much! I really like your approach, I was looking at this problem from too wide of a perspective. I really appreciate it! Commented Jan 12, 2019 at 21:28
ClearAll[chainedQ]
chainedQ = And @@ BlockMap[Or @@ Equal @@@ Transpose@#[[All, {1, -1}]] &, #, 2, 1] &;

Select[list, chainedQ]

{{{1}, {1, 2}, {1, 2, 3}}, {{2}, {1, 2}, {1, 2, 3}}, {{2}, {2, 3}, {1, 2, 3}}, {{3}, {2, 3}, {1, 2, 3}}}

Pick[list, chainedQ /@ list]

{{{1}, {1, 2}, {1, 2, 3}}, {{2}, {1, 2}, {1, 2, 3}}, {{2}, {2, 3}, {1, 2, 3}}, {{3}, {2, 3}, {1, 2, 3}}}