整数范围重叠验证

时间:2014-02-17 15:43:05

标签: c# .net overlap range

我在论坛上看过几个帖子,但目前还没有明确的答案。我想查看一个年龄列表。我想确保年龄范围不重叠。关键点是开始和结束年龄可以是相同的数字,这不应该导致找到重叠。

任何帮助都会很棒

示例代码

namespace RangeValidation
{
    public class RangeValidate
    {
        private readonly IList<Age> _listOfRanges = new List<Age>();
        private readonly IList<Age> _secondListOfRanges = new List<Age>();
    public void Validate()
    {
        _listOfRanges.Add(new Age { BeginingAge = 20, EndingAge = 20 });
        _listOfRanges.Add(new Age { BeginingAge = 21, EndingAge = 30 });
        _listOfRanges.Add(new Age { BeginingAge = 31, EndingAge = 60 });


        _secondListOfRanges.Add(new Age { BeginingAge = 20, EndingAge = 20 });
        _secondListOfRanges.Add(new Age { BeginingAge = 20, EndingAge = 30 });

        _secondListOfRanges.Add(new Age { BeginingAge = 31, EndingAge = 60 });

        Debug.Write(Overlaps(_listOfRanges).ToString()); // NO OVERLAPS
        Debug.Write(Overlaps(_secondListOfRanges).ToString()); // Has overlaps

    }

    private static bool Overlaps(IEnumerable<Age> listOfRanges)
    {
        return true; // needs implementation here
    }
}

public class Age
{
    public int BeginingAge
    {
        get;
        set;
    }

    public int EndingAge
    {
        get;
        set;
    }
}

}

2 个答案:

答案 0 :(得分:4)

此代码适用于您:

private static bool Overlaps(IEnumerable<Age> listOfRanges)
{
    bool isOverlaps = false;

    foreach (var range in listOfRanges)
    {
        if (listOfRanges.Count(x => 
            (x.BeginingAge >= range.BeginingAge && x.BeginingAge <= range.EndingAge) 
            || (x.EndingAge >= range.BeginingAge && x.EndingAge <= range.EndingAge)) > 1)
        {
            isOverlaps = true;
            break;
        }
    }

    return isOverlaps;
}

但正如哈里森所说,尝试自己编写这段代码是个好主意。也许会有更好的解决方案然后开采,但它确实有效。

答案 1 :(得分:0)

O(n log n)解决方案:

private static bool Overlaps(IEnumerable<Age> listOfRanges)
{
    List<Age> sorted = listOfRanges.OrderBy(o=>o.BeginingAge).ToList();
    for(int i=1; i<sorted.Count; ++i)
    {
        if(sorted[i-1].EndingAge > sorted[i].BeginingAge) //change to >= is needed
            return false;
    }
    return true;
}