# Selecting cases from a list based on two conditions

Let's say we have a list of lists of length 3, as below:

 {{{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}}}


Now, from that list I want to extract those lists which satisfy the following rules:

1) neighbouring elements in the list have either the same first element or last element, e.g. {{1},{1,2},{1,2,3}} or {{2},{2,3},{1,2,3}}.

2) when there are more than one element of length 1 in the list, we take the difference of all such pairs of elements. If that difference is not equal to the absolute value of 1 for all such pairs and the rest of the elements of that list satisfy Rule 1., we pick that list. We keep in mind that the lists in the list below can be of any length. So for example, we would pick {{1},{3},{1,2,3}} but not {{1},{2},{1,2,3}}.

Applying those 2 rules to the list above we would get:

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


I kind of want to avoid using loops but if that's the only possibility then that's fine. If someone can see some different rules that would allow us the get the same output from that list above then I'd love to see it too. Any help is much appreciated.

• (1) you can get using SplitBy[lst, #[[{1, -1}]] &] – kglr Jan 11 at 18:11
• Thank you! Didn't know about this function, I'm very new to Mathematica. – amator2357 Jan 11 at 18:20
• amator2357, my pleasure; welcome to mma.se. – kglr Jan 11 at 18:31
• This question is crossposted here – Rohit Namjoshi Jan 12 at 23:10

Table[Select[test3,First[#[[i+1]]]==First[#[[i]]] \[Or] Last[#[[i+1]]]==Last[#[[i]]] &],{i,n-2}]

• The solution proposed by @kglr does not result in the same list. Compare MatrixForm@lst and MatrixForm@SplitBy[lst, #[[{1, -1}]] &] – Rohit Namjoshi Jan 12 at 23:09