Ordered Subsequences of consecutive integers
Select[Split[list, #2 - #1 == 1 &], Length[#] > 1 &]
Also can get the same result
Didn't find an exact duplicate so let's use another closely related:
How to detect if a sequence of integers is consecutive, credits to Simon Woods
consecutiveQ = Most[#] == Rest[#] - 1 &
SequenceCases[{3, 4, 8, 1, 2, 5, 6, 7, 9}, {_, __}?consecutiveQ]
{{3, 4}, {1, 2}, {5, 6, 7}}
Based on intervals
from Find subsequences of consecutive integers inside a list:
consec[a_List] :=
SparseArray[Differences@a, Automatic, 1]["AdjacencyLists"] //
{a[[Prepend[# + 1, 1]]], a[[Append[#, -1]]]} & //
Range @@@ Pick[#\[Transpose], Unitize[Subtract @@ #], 1] &
consec[{3, 4, 8, 1, 2, 5, 6, 7, 9}]
{{3, 4}, {1, 2}, {5, 6, 7}}
Benchmark including the two existing answers as fnK
and fnY
:
consecutiveQ = Most[#] == Rest[#] - 1 &;
fnK[lst_] := SequenceCases[lst, {_, __}?consecutiveQ]
fnY[lst_] := Select[Split[lst, #2 - #1 == 1 &], Length[#] > 1 &]
Needs["GeneralUtilities`"]
BenchmarkPlot[{fnK, fnY, consec}, RandomInteger[9, #] &, 2]
(Note the log-log scale.)