5
$\begingroup$

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

$\endgroup$
3
  • 3
    $\begingroup$ Would Split[list, #2 - #1 == 1 &] do? However I'm not sure why 7 and 9 are grouped together in your output. $\endgroup$
    – MarcoB
    Commented Aug 9, 2022 at 1:04
  • $\begingroup$ @Macob Exactly what I want! Short and Efficacious!! Thanks. Yes, I was wrong on the 7 and the. They are not grouped. $\endgroup$ Commented Aug 9, 2022 at 2:54
  • $\begingroup$ Great! I've posted it as an answer then! $\endgroup$
    – MarcoB
    Commented Aug 9, 2022 at 14:47

5 Answers 5

7
$\begingroup$
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}}
*)
$\endgroup$
5
$\begingroup$

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.)

$\endgroup$
1
  • $\begingroup$ Thanks, But I wanted a group by arithmetic progression with a common difference of 1. MarcoB's solution works fine for me with "Split". $\endgroup$ Commented Aug 9, 2022 at 3:06
2
$\begingroup$
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}}

$\endgroup$
1
$\begingroup$
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}}

$\endgroup$
0
$\begingroup$
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}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.