[swift-users] difference between two Ranges

Nevin Brackett-Rozinsky nevin.brackettrozinsky at gmail.com
Wed Sep 20 15:23:04 CDT 2017


I think you’ll have to write this functionality yourself.

If you start with one range and remove from it everything in another range,
you will end up with either:

i) An empty range, if the first is entirely within the second.
ii) A single range, which might be closed, open, or half-open on either end.
iii) Two ranges, if the second is entirely within the first.

Of course, the built-in range types don’t cover all the possible
opennesses. So you probably want to do something like the following:

• Create your own range type (or types) to handle the various open/closed
possibilities.
• Create your own “collection of ranges” type (probably implemented with an
array of ranges).
• Write methods to handle combining and subtracting ranges and collections
thereof.

You should end up with something whereby subtracting one range from another
creates a collection of ranges, and adding a range to a collection merges
together any ranges that now overlap (keeping the ranges in the collection
disjoint means you can keep the array sorted in the natural manner).

Nevin


On Wed, Sep 20, 2017 at 4:09 PM, Седых Александр via swift-users <
swift-users at swift.org> wrote:

> Hello.
> I try to get difference between two ranges. For instance I have to know
> how many meters from me to target who have own size (or range).
>
> let range = 0...5
>
> let meFromPoint = 0...10
>
>
>
> let setRange = Set(range)
>
> let setMeFromPoint = Set(meFromPoint)
>
>
>
> let diff = setMeFromPoint.subtracting(setRange).count// result 5
>
> I found that operation Set(0...veryBigInt) may be slow.
> Is exist some native way to get difference between two Ranges?
>
>
> --
> Седых Александр
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170920/5ccd5491/attachment.html>


More information about the swift-users mailing list