5
$\begingroup$

I've encountered a particular problem and was wondering if anyone has any insights on how to approach it more efficiently or elegantly.

To be accurate, given the list:

list = {2, 5, 8, 12, 16, 20, 24, 28, 31};

I'm looking to generate pairs of consecutive elements in the following manner:

{{1, 2}, {3, 5}, {6, 8}, {9, 12}, {13, 16}, {17, 20}, {21, 24}, {25, 28}, {29, 31}}

Currently, I'm using the following code:

Table[{If[i == 1, 0, list[[i - 1]]] + 1, list[[i]]}, {i, 1, Length@list}]

The above code works, but I'm interested in knowing if there is a more elegant or efficient way to achieve the same result.

I would appreciate any suggestions or alternative approaches anyone in the community may have. Thanks in advance!

$\endgroup$

2 Answers 2

4
$\begingroup$
Clear["Global`*"];
list = {2, 5, 8, 12, 16, 20, 24, 28, 31};
res = {{1, 2}, {3, 5}, {6, 8}, {9, 12}, {13, 16}, {17, 20}, {21, 
   24}, {25, 28}, {29, 31}};

listplusone = Most[1 + # & /@ {0}~Join~list]
Transpose[{listplusone, list}] == res

True

$\endgroup$
3
  • $\begingroup$ (+1) Nicely done, @Syed! I'll just wait for at least one more answer to make a comparison with yours, and then accept the answer. :-) $\endgroup$ Commented Jan 15 at 2:48
  • 1
    $\begingroup$ listplusone = Most[1 + {0}~Join~list] would also be okay. $\endgroup$
    – Syed
    Commented Jan 15 at 5:02
  • 1
    $\begingroup$ The suggested change looks very elegant: Transpose[{Most[1 + {0}~Join~#], #}] &@list $\endgroup$ Commented Jan 15 at 5:29
4
$\begingroup$
list = {2, 5, 8, 12, 16, 20, 24, 28, 31};

Using SequenceCases

SequenceCases[Prepend[list, 0], {a_, b_} :> {a + 1, b}, Overlaps -> True]

{{1, 2}, {3, 5}, {6, 8}, {9, 12}, {13, 16}, {17, 20}, {21, 24}, {25, 28}, {29, 31}}

$\endgroup$
1
  • $\begingroup$ (+1) Your solution is also very nice, @eldo, because I like using the functions dedicated to sequences. :-) $\endgroup$ Commented Jan 15 at 8:06

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.