5
$\begingroup$

Given a list, I want to find all possible ways to split it into sublists such that:

  1. Each sublist has length greater than 1.
  2. Any two consecutive sublists share exactly one common element.
  3. All elements of the original list are included in the sublists.

For example, for the input:

list = {1, 2, 3, 4, 5}; 

Some possible splits would be:

{{1, 2}, {2, 3}, {3, 4, 5}} {{1, 2}, {2, 3, 4, 5}} {{1, 2, 3}, {3, 4, 5}} ... {{1, 2, 3, 4, 5}} 
$\endgroup$

4 Answers 4

9
$\begingroup$
list = {1, 2, 3, 4, 5}; (Prepend @@@ Transpose[{#, Prepend[Most[#][[All, -1]], {}]}] /. {} -> Nothing) & /@ (TakeList[list, #] & /@ Select[Flatten[Permutations /@ IntegerPartitions[Length[list]], 1], #[[1]] != 1 &]) 

{{1,2,3,4,5}} {{1,2,3,4},{4,5}} {{1,2,3},{3,4,5}} {{1,2},{2,3,4,5}} {{1,2,3},{3,4},{4,5}} {{1,2},{2,3,4},{4,5}} {{1,2},{2,3},{3,4,5}} {{1,2},{2,3},{3,4},{4,5}} 

Or maybe simpler:

list = {1, 2, 3, 4, 5}; Split[#, Not@* SameQ] & /@ (Flatten[ list /. Thread[# -> Replace[#, x_ -> {x, x}, 1]]] & /@ Subsets[list[[2 ;; -2]]]) 

{{1,2,3,4,5}} {{1,2},{2,3,4,5}} {{1,2,3},{3,4,5}} {{1,2,3,4},{4,5}} {{1,2},{2,3},{3,4,5}} {{1,2},{2,3,4},{4,5}} {{1,2,3},{3,4},{4,5}} {{1,2},{2,3},{3,4},{4,5}} 
$\endgroup$
6
$\begingroup$
With[{n = Length[list] - 2}, FoldList[Prepend[#2, Last[#]] &, TakeList[list, Append[#, All]]] & /@ Differences /@ Join[ConstantArray[-1, {2^n, 1}], Subsets[Range[n]], 2]] 

{{{1, 2, 3, 4, 5}}, {{1, 2}, {2, 3, 4, 5}}, {{1, 2, 3}, {3, 4, 5}}, {{1, 2, 3, 4}, {4, 5}}, {{1, 2}, {2, 3}, {3, 4, 5}}, {{1, 2}, {2, 3, 4}, {4, 5}}, {{1, 2, 3}, {3, 4}, {4, 5}}, {{1, 2}, {2, 3}, {3, 4}, {4, 5}}}

Or

With[{n = Length[list]}, list[[# ;; #2]] & @@@ Partition[Join[{1}, #, {n}], 2, 1] & /@ Subsets[Range[2, n - 1]]] 
$\endgroup$
5
$\begingroup$

Another method:

list = {1, 2, 3, 4, 5}; Map[ Take[list, #] &, Partition[#, 2, 1] & /@ Flatten /@ Tuples[MapAt[Subsets, TakeList[list, {1, Length[list] - 2, 1}], 2]], {-2}] (* {{{1, 2, 3, 4, 5}}, {{1, 2}, {2, 3, 4, 5}}, {{1, 2, 3}, {3, 4, 5}}, {{1, 2, 3, 4}, {4, 5}}, {{1, 2}, {2, 3}, {3, 4, 5}}, {{1, 2}, {2, 3, 4}, {4, 5}}, {{1, 2, 3}, {3, 4}, {4, 5}}, {{1, 2}, {2, 3}, {3, 4}, {4, 5}}} *) 
$\endgroup$
2
$\begingroup$

A graph-based method:

list = Range[5]; With[{g = RelationGraph[Last@# == First@#2 & , Subsequences[list, {2, Length@list}]]}, Prepend[{list}]@ Flatten[MapApply[FindPath[g, #, #2, Infinity, All] & , Tuples[Map[Pick[VertexList[g], #, 0] &]@ Comap[{VertexInDegree, VertexOutDegree}]@g]], 1]] 
(*{{{1, 2, 3, 4, 5}} , {{1, 2}, {2, 3, 4}, {4, 5}} , {{1, 2}, {2, 3}, {3, 4}, {4, 5}} , {{1, 2}, {2, 3}, {3, 4, 5}} , {{1, 2}, {2, 3, 4, 5}} , {{1, 2, 3}, {3, 4}, {4, 5}} , {{1, 2, 3}, {3, 4, 5}} , {{1, 2, 3, 4}, {4, 5}}}*) 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.