I have a list= {4, 8, 10, 11, 12, 14, 16, 7, 9}
How can i partition the list by group of Arithmetic Progression with common difference 1 :
{{4}, {8}, { 10, 11, 12}, {14}, {16}, {7}, {9}}
list= {4, 8, 10, 11, 12, 14, 16, 7, 9};
Split[list, #2 - #1 == 1 &]
(* Out:
{{4}, {8}, {10, 11, 12}, {14}, {16}, {7}, {9}}
*)
I think there is some ambiguity here. {4,8}
could certainly be an arithmetic progression. Also, why not {14,16}
? Anyway, here's my attempt. It gives something different that your expected output, but I think it satisfies the requirement that each group is an arithmetic progression.
MakeArithGroups[list : {_}] := list;
MakeArithGroups[list : {_, _}] := list;
MakeArithGroups[list : {a_, b_, rest__}] := MakeArithGroups[{{a, b}}, {rest}];
MakeArithGroups[prev : {___List}, {}] := prev;
MakeArithGroups[prev : {___List, {a_, b_, ___}}, rest : {x_, ___}] :=
If[
x - b == b - a,
MakeArithGroups[Insert[prev, x, {-1, -1}], Rest@rest],
MakeArithGroups[Insert[prev, Take[rest, UpTo[2]], -1], Drop[rest, UpTo[2]]]]
Demo:
MakeArithGroups[{4, 8, 10, 11, 12, 14, 16, 7, 9}]
(* {{4, 8}, {10, 11, 12}, {14, 16}, {7, 9}} *)
(This has only been lightly tested.)
list = {4, 8, 10, 11, 12, 14, 16, 7, 9};
Using SequenceCases
SequenceCases[list, x_ /; OrderedQ[x, #2 - #1 == 1 &]]
{{4}, {8}, {10, 11, 12}, {14}, {16}, {7}, {9}}
list = {4, 8, 10, 11, 12, 14, 16, 7, 9};
Using SequenceSplit
:
SequenceSplit[list, x_ /; OrderedQ[x, #2 - #1 == 1 &] :> x]
{{4}, {8}, {10, 11, 12}, {14}, {16}, {7}, {9}}
list = {4, 8, 10, 11, 12, 14, 16, 7, 9};
SequenceReplace[list, {a__} /;
ContainsOnly[Differences[{a}], {1}] :> {a}]
{{4}, {8}, {10, 11, 12}, {14}, {16}, {7}, {9}}
Split[list, #2 - #1 == 1 &]
do? However I'm not sure why 7 and 9 are grouped together in your output. $\endgroup$