10
$\begingroup$

If I have a list

list={3,7,4,5,1}

how to get the List of Intervals /Ranges

result = {{1,3},{3,4},{4,5},{5,7}}
$\endgroup$

2 Answers 2

18
$\begingroup$

Maybe

Partition[Sort@list, 2, 1]

giving

{{1, 3}, {3, 4}, {4, 5}, {5, 7}}

$\endgroup$
1
  • $\begingroup$ Beat me to it - 7 secs! Deleting mine, and +1. $\endgroup$ Jan 21, 2012 at 9:30
7
$\begingroup$

Tom's answer is canonical, but you could also use:

With[{s = Sort[list]}, Transpose[{Most[s], Rest[s]}]]

which seems to be marginally faster for large lists. (In which case most of the time is spent sorting.)

$\endgroup$
1
  • 2
    $\begingroup$ Alternatively: Composition[Transpose, Through, {Most, Rest}, Sort][list]. $\endgroup$ Jan 22, 2012 at 4:26

Your Answer

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

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