Check for missing number in sequence

前端 未结 14 1547
太阳男子
太阳男子 2020-12-04 17:58

I have an List which contains 1,2,4,7,9 for example.

I have a range from 0 to 10.

Is there a way to determine what numbers are missin

14条回答
  •  粉色の甜心
    2020-12-04 18:05

    Ok, really, create a new list which parallels the initial list and run the method Except over it...

    I have created a fully linq answer using the Aggregate method instead to find the missings:

    var list = new List(new[] { 1, 2, 4, 7, 9 }); // Assumes list is ordered at this point
    
    list.Insert(0, 0);   // No error checking, just put in the lowest and highest possibles.
    list.Add(10);        // For real world processing, put in check and if not represented then add it/them.
    
    var missing = new List();    // Hold any missing values found.
    
    list.Aggregate ((seed, aggr) =>   // Seed is the previous #, aggr is the current number.
    {
        var diff = (aggr - seed) -1;  // A difference between them indicates missing.
    
        if (diff > 0)                 // Missing found...put in the missing range.
            missing.AddRange(Enumerable.Range((aggr - diff), diff));
    
        return aggr;    
    });
    

    The missing list has this after the above code has been executed:

    3, 5, 6, 8
    

提交回复
热议问题