How to detect if a sequence of integers is consecutive
IF you can assume 1) they are integers, 2) they are ascending, and 3) no repeats, THEN your last idea should work
Last[list]-First[list]==Length[list]-1
Or you could
Union[Differences[list]]=={1}
Without assumptions (2) and (3):
Union[Differences[Sort[list]]]=={1}
A short one:
consecutiveQ = Most[#] == Rest[#] - 1 &
From Stack Overflow: How to test if a list contains consecutive integers in Mathematica?
See rcollyer's comparative timings.
My concise form of belisarius's method from that thread was:
Range[##, Sign[#2 - #]]& @@ #[[{1, -1}]] == # &;
It checks for consecutive numbers in either direction. It however will consume memory or outright fail in the case where the first and last values in the test list are far apart because of the Range
generation:
Range[##, Sign[#2 - #]]& @@ #[[{1, -1}]] == # &[{1, 2, 1*^50}]
Range::range: Range specification in Range[1,100000000000000000000000000000000000000000000000000,1] does not have appropriate bounds. >>
Here is an updated approach that does some sanity checks first:
consecutiveQ[x : {first_, ___, last_}] :=
And[
Min[x] == first,
Max[x] == last,
Length[x] == last - first + 1,
Range[first, last] == x
]
consecutiveQ /@ {a1, a2, a3, a4, a5, a6}
{True, True, False, True, False, True}
It only checks for forward-increasing sequences as that is what is shown in this question. It could be easily adapted for backward sequences as well if needed.
If your valid input lists will always contain integers you could add the condition:
VectorQ[x, IntegerQ]
Otherwise as written the the test will return True
for e.g. consecutiveQ[{7., 8., 9.}]
.