List dansConList = new List();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;
List dansRandomList = new List
Here is a C version code, I think it's easy to rewrite it in other language based on the logical.
int isConsecutive(int *array, int length) {
int i = 1;
for (; i < length; i++) {
if (array[i] != array[i - 1] + 1)
return 0; //which means false and it's not a consecutive list
}
return 1;
}
You can use this extension method:
public static bool IsConsecutive(this IEnumerable<int> ints )
{
//if (!ints.Any())
// return true; //Is empty consecutive?
// I think I prefer exception for empty list but I guess it depends
int start = ints.First();
return !ints.Where((x, i) => x != i+start).Any();
}
Use it like this:
[Test]
public void ConsecutiveTest()
{
var ints = new List<int> {1, 2, 4};
bool isConsecutive = ints.IsConsecutive();
}
// 1 | 2 | 3 | 4 | _
// _ | 1 | 2 | 3 | 4
// | 1 | 1 | 1 | => must be 1 (or 2 for even/odd consecutive integers)
var numbers = new List<int>() { 1, 2, 3, 4, 5 };
const step = 1; // change to 2 for even and odd consecutive integers
var isConsecutive = numbers.Skip(1)
.Zip(numbers.SkipLast(1))
.Select(n => {
var diff = n.First - n.Second;
return (IsValid: diff == step, diff);
})
.Where(diff => diff.IsValid)
.Distinct()
.Count() == 1;
Or we could write that a bit shorter but less readable:
var isConsecutive = numbers.Skip(1)
.Zip(numbers.SkipLast(1), (l, r) => (IsValid: (l-r == step), l-r))
.Where(diff => diff.IsValid)
.Distinct()
.Count() == 1;
Here is the another one. It supports {1,2,3,4} and {4,3,2,1} both. It tests sequential number differences equals 1 or -1.
Function IsConsecutive(ints As IEnumerable(Of Integer)) As Boolean
If ints.Count > 1 Then
Return Enumerable.Range(0, ints.Count - 1).
All(Function(r) ints(r) + 1 = ints(r + 1) OrElse ints(r) - 1 = ints(r + 1))
End If
Return False
End Function
var min = list.Min();
var max = list.Max();
var all = Enumerable.Range(min, max - min + 1);
return list.SequenceEqual(all);
Caveat: returns true if empty.
var list = new int[] {-1,0,1,2,3};
var isConsecutive = list.Select((n,index) => n == index+list.ElementAt(0)).All (n => n);