Advertisement
HXXXXJ

NSRange intersection

Mar 23rd, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.85 KB | None | 0 0
  1.  
  2. struct NSRange {
  3.   location : Int;
  4.     length : Int;
  5. }
  6. typealias NSNotFound = Int.max
  7.  
  8. //**证明相交最简单的办法就是 -> 证明不是不相交**
  9.  
  10. func intersection(_ r1 : NSRange, _ r2 : NSRange) -> NSRange{
  11.     guard r1.location != NSNotFound && r1.length != NSNotFound
  12.     && r2.location != NSNotFound && r2.length != NSNotFound  else{
  13.         return NSRange(location: NSNotFound, length: NSNotFound)
  14.     }
  15.     //check if intersection
  16.     if r1.location + r1.length - 1 < r2.location || r2.location + r2.length - 1 < r1.location {
  17.         return NSRange(location: NSNotFound, length: NSNotFound)
  18.     }
  19.    
  20.     //get intersection
  21.     let startIndex = max(r1.location, r2.location)
  22.     let endIndex = min(r1.location + r1.length - 1, r2.location + r2.length - 1)
  23.     return NSRange(location: startIndex, length: endIndex - startIndex + 1)
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement