Functional way to check if array of numbers is sequential

前端 未结 7 1818
无人共我
无人共我 2020-12-16 14:32

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,

相关标签:
7条回答
  • 2020-12-16 15:01

    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.

    0 讨论(0)
  • 2020-12-16 15:05

    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");
     }
    
    0 讨论(0)
  • 2020-12-16 15:06

    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.

    0 讨论(0)
  • 2020-12-16 15:06
    var result = Enumerable.Range(array[0], array[array.Length-1]).Except(array.ToList());
    
    0 讨论(0)
  • 2020-12-16 15:07

    Try this one:

        bool IsSequential(int[] array)
        {
            return array.Zip(array.Skip(1), (a, b) => (a + 1) == b).All(x => x);
        }
    
    0 讨论(0)
  • 2020-12-16 15:11

    Using Linq:

        public static bool IsSequential(int[] a)
        {
            return Enumerable.Range(1, a.Length - 1).All(i => a[i] - 1 == a[i - 1]);
        }
    
    0 讨论(0)
提交回复
热议问题