Question

I have seen several posts on the forum but no definite answer as of yet. I want to check a list of ages. I want to ensure that the ages ranges do not overlap. The key point is a beginning and and ending age CAN be the same number, this should not cause a found overlap.

Any help would be great

Sample code

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

}

Was it helpful?

Solution

This code should work for you:

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

But as Harrison said it would be a good idea to try writing this code by your own. Maybe there will be a better solution then mines, but it works.

OTHER TIPS

An O(n log n) solution:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top