3
$\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
    Aug 9 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$ Aug 9 at 2:54
  • $\begingroup$ Great! I've posted it as an answer then! $\endgroup$
    – MarcoB
    Aug 9 at 14:47

2 Answers 2

4
$\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$ Aug 9 at 3:06
4
$\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$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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