簡體   English   中英

檢查是否列出<Int32>值是連續的

[英]Check if List<Int32> values are consecutive

List<Int32> dansConList = new List<Int32>();
dansConList[0] = 1;
dansConList[1] = 2;
dansConList[2] = 3;

List<Int32> dansRandomList = new List<Int32>();
dansRandomList[0] = 1;
dansRandomList[1] = 2;
dansRandomList[2] = 4;

我需要一種方法,在評價上述列表時,會返回falsedansRandomListtruedansConList基於這樣的事實dansConList在它的值連續數列,並dansRandomList沒有(缺值3)。

如果可能,最好使用 LINQ。

我試過的:

  • 為了獲得最終結果,我使用了 for 循環並與 'i'(循環計數器)進行比較來評估值,但如上所述,我想為此使用 LINQ。

單行,只迭代到第一個不連續的元素:

bool isConsecutive = !myIntList.Select((i,j) => i-j).Distinct().Skip(1).Any();

更新:這是如何工作的幾個例子:

Input is { 5, 6, 7, 8 }
Select yields { (5-0=)5, (6-1=)5, (7-2=)5, (8-3=)5 }
Distinct yields { 5, (5 not distinct, 5 not distinct, 5 not distinct) }
Skip yields { (5 skipped, nothing left) }
Any returns false
Input is { 1, 2, 6, 7 }
Select yields { (1-0=)1, (2-1=)1, (6-2=)4, (7-3=)4 } *
Distinct yields { 1, (1 not distinct,) 4, (4 not distinct) } *
Skip yields { (1 skipped,) 4 }
Any returns true

* Select 不會產生第二個 4 並且 Distinct 不會檢查它,因為 Any 將在找到第一個 4 后停止。

var min = list.Min();
var max = list.Max();
var all = Enumerable.Range(min, max - min + 1);
return list.SequenceEqual(all);
var result = list
    .Zip(list.Skip(1), (l, r) => l + 1 == r)
    .All(t => t);

您可以使用此擴展方法:

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

像這樣使用它:

[Test]
public void ConsecutiveTest()
{
    var ints = new List<int> {1, 2, 4};
    bool isConsecutive = ints.IsConsecutive();
}

擴展方法:

public static bool IsConsecutive(this IEnumerable<int> myList)
{
    return myList.SequenceEqual(Enumerable.Range(myList.First(), myList.Last()));
}

用途:

bool isConsecutive = dansRandomList.IsConsecutive();

這是另一個。 它同時支持 {1,2,3,4} 和 {4,3,2,1}。 它測試序列號差異是否等於 1 或 -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

警告:如果為空,則返回 true。

var list = new int[] {-1,0,1,2,3};
var isConsecutive = list.Select((n,index) => n == index+list.ElementAt(0)).All (n => n);

為了檢查系列是否包含連續數字,您可以使用它

樣本

isRepeatable(121878999, 2);

結果 = 真

由於 9 重復了兩次,其中 upto 是連續次數

isRepeatable(37302293, 3)

結果 = 錯誤

因為沒有數字連續重復 3 次

static bool isRepeatable(int num1 ,int upto)
    {
        List<int> myNo = new List<int>();
        int previous =0;
        int series = 0;
        bool doesMatch = false;
        var intList = num1.ToString().Select(x => Convert.ToInt32(x.ToString())).ToList();
        for (int i = 0; i < intList.Count; i++)
        {
            if (myNo.Count==0)
            {
                myNo.Add(intList[i]);
                previous = intList[i];
                series += 1;
            }
            else
            {
                if (intList[i]==previous)
                {
                    series += 1;
                    if (series==upto)
                    {
                        doesMatch = true;
                        break;
                    }
                }
                else
                {
                    myNo = new List<int>();
                    previous = 0;
                    series = 0;
                }
            }
           
        }

        return doesMatch;

    }
// 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;

或者我們可以寫得更短但可讀性較差:

var isConsecutive = numbers.Skip(1)
   .Zip(numbers.SkipLast(1), (l, r) => (IsValid: (l-r == step), l-r))
   .Where(diff => diff.IsValid)
   .Distinct()
   .Count() == 1;

老問題,但這是使用一些簡單代數的簡單方法。

不過,這只適用於您的整數從 1 開始的情況。

public bool AreIntegersConsecutive(List<int> integers)
{
    var sum = integers.Sum();
    var count = integers.Count();
    var expectedSum = (count * (count + 1)) / 2;

    return expectedSum == sum;
}

它僅適用於唯一列表。

List<Int32> dansConList = new List<Int32>();
dansConList.Add(7);
dansConList.Add(8);
dansConList.Add(9);

bool b = (dansConList.Min() + dansConList.Max())*((decimal)dansConList.Count())/2.0m == dansConList.Sum();

這是一個使用Aggregate函數的擴展方法。

public static bool IsConsecutive(this List<Int32> value){
    return value.OrderByDescending(c => c)
                .Select(c => c.ToString())
                .Aggregate((current, item) => 
                            (item.ToInt() - current.ToInt() == -1) ? item : ""
                            )
                .Any();
}

用法:

var consecutive = new List<Int32>(){1,2,3,4}.IsConsecutive(); //true
var unorderedConsecutive = new List<Int32>(){1,4,3,2}.IsConsecutive(); //true
var notConsecutive = new List<Int32>(){1,5,3,4}.IsConsecutive(); //false

這是一個C版本的代碼,我認為根據邏輯用其他語言重寫它很容易。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM