Let\'s say that an array is sequential when each successful element has the value of previous element + 1
. Suppose I have an array of numbers like {5,6,7,
First sort the array, remove N of a kind (e.g. pairs) using distinct() and If the array length is always == to 5 All you need to do is if((array[4] - array[0]) == 4) return true.
It gets more complicated if its texas holdem or if you need to account for both an ace high and ace low straight.
This should do the trick, for all sequential, non sequential data. A complete example with sample input. Tested and works fine
var list = new List<int>(new[] { 7, 6, 5, 4, 3,9});
int minValue = list.Min();
int maxValue = list.Count;
List<int> test = Enumerable.Range(minValue, maxValue).ToList();
var result = Enumerable.Range(minValue, maxValue).Except(list);
if (result.ToList().Count == 0)
{
Console.WriteLine("numbers are in sequence");
}
else
{
Console.WriteLine("Numbers are not in sequence");
}
I don't know if it's really an improvement/nicer but you could use Range.
ENumerable.Range(0, myArray.Length).Any(i => myArray[i] != myArray[0] + i)
This returns true if the array doesn't contain sequential number.
var result = Enumerable.Range(array[0], array[array.Length-1]).Except(array.ToList());
Try this one:
bool IsSequential(int[] array)
{
return array.Zip(array.Skip(1), (a, b) => (a + 1) == b).All(x => x);
}
Using Linq:
public static bool IsSequential(int[] a)
{
return Enumerable.Range(1, a.Length - 1).All(i => a[i] - 1 == a[i - 1]);
}