Axarydax
Axarydax

Reputation: 16603

Functional way to check if array of numbers is sequential

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,8} (sequential) or {1,2,5} (not sequential).

Is there a nice functional way to check if the array is sequential? I can do it with the following code:

bool IsSequential(int[] array)
{
    for (int i = 1; i < array.Length; i++)
       if (array[i] != array[i - 1] + 1)
            return false;
    return true;
}

I'm trying to determine if a poker hand is straight.

Upvotes: 18

Views: 16853

Answers (8)

Jeffrey Zhang
Jeffrey Zhang

Reputation: 438

Try this one, I think it is most simple:

nums.Select((n, i) => n - i).Distinct().Count() == 1

Upvotes: 1

Asmussen
Asmussen

Reputation: 468

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.

Upvotes: 0

Serge
Serge

Reputation: 6692

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.

Upvotes: 8

sara
sara

Reputation: 3934

Same as: make sure array is sequential in C#

Answer there:

if you're sure that the array is sorted and has no duplicates, you can just check:

array[array.Length - 1] == array[0] + array.Length - 1

Upvotes: 1

Ehsan
Ehsan

Reputation: 32681

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");
 }

Upvotes: 2

JDunkerley
JDunkerley

Reputation: 12495

Using Linq:

    public static bool IsSequential(int[] a)
    {
        return Enumerable.Range(1, a.Length - 1).All(i => a[i] - 1 == a[i - 1]);
    }

Upvotes: 2

AKD
AKD

Reputation: 3966

var result = Enumerable.Range(array[0], array[array.Length-1]).Except(array.ToList());

Upvotes: 1

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

Try this one:

    bool IsSequential(int[] array)
    {
        return array.Zip(array.Skip(1), (a, b) => (a + 1) == b).All(x => x);
    }

Upvotes: 22

Related Questions