2014-02-17 45 views
-2

我在论坛上看到过几篇文章,但至今没有明确的答案。我想检查一个年龄列表。我想确保年龄范围不重叠。关键是开始和结束年龄可以是相同的数字,这不应该导致发现重叠。整数范围重叠验证

任何帮助将是巨大的

示例代码

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

}

+3

在你对应该重叠什么代码中的注释似乎是在与你的开始和结束的年龄文本赔率被允许是相同的... – Paddy

+1

虽然你有代码显示你的设置/要求,你还没有试图编写代码。请尝试一下,然后告诉我们您遇到问题的位置。 – Harrison

回答

3

此代码应为你工作:

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

但哈里森说,这将是一个很好想法尝试写你自己的代码。也许会有一个更好的解决方案,然后矿,但它的作品。

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