Check if List values are consecutive

前端 未结 12 1813
悲&欢浪女
悲&欢浪女 2021-02-01 05:46
List dansConList = new List();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;

List dansRandomList = new List

        
相关标签:
12条回答
  • 2021-02-01 06:33

    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;
    }
    
    0 讨论(0)
  • 2021-02-01 06:37

    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();
    }
    
    0 讨论(0)
  • 2021-02-01 06:38
    // 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;
    
    0 讨论(0)
  • 2021-02-01 06:40

    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
    
    0 讨论(0)
  • 2021-02-01 06:41
    var min = list.Min();
    var max = list.Max();
    var all = Enumerable.Range(min, max - min + 1);
    return list.SequenceEqual(all);
    
    0 讨论(0)
  • 2021-02-01 06:41

    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);
    
    0 讨论(0)
提交回复
热议问题