Giter Club home page Giter Club logo

segment_tree's Introduction

SegmentTree Build Status

Ruby implementation of segment tree data structure. Segment tree is a tree data structure for storing intervals, or segments. It allows querying which of the stored segments contain a given point. It is, in principle, a static structure; that is, its content cannot be modified once the structure is built.

Segment tree storage has the complexity of O(n). Segment tree querying has the complexity of O(log n).

It's pretty fast on querying trees with ~ 10 millions segments, though building of such big tree will take long. Internally it is not a tree - it is just a sorted array, and querying the tree is just a simple binary search (it was implemented as real tree in versions before 0.1.0, but these trees consumed a lot of memory).

Installation

Add this line to your application's Gemfile:

gem 'segment_tree'

And then execute:

$ bundle

Or install it yourself as:

$ gem install segment_tree

Usage

Segment tree consists of segments (in Ruby it's Range objects) and corresponding values. The easiest way to build a segment tree is to create it from hash where segments are keys:

tree = SegmentTree.new(1..10 => "a", 11..20 => "b", 21..30 => "c") # => #<SegmentTree:0xa47eadc @root=#<SegmentTree::Container:0x523f3b6 @range=1..30>>

After that you can query the tree of which segment contains a given point:

tree.find(5) # => #<SegmentTree::Segment:0xa47ea8c @range=1..10, @value="a">

Real world example

Segment tree can be used in applications where IP-address geocoding is needed.

data = [
  [IPAddr.new('87.224.241.0/24').to_range, {:city => "YEKT"}],
  [IPAddr.new('195.58.18.0/24').to_range, {:city => "MSK"}]
  # and so on
]
ip_tree = SegmentTree.new(data)

client_ip = IPAddr.new("87.224.241.66")
ip_tree.find(client_ip).value # => {:city=>"YEKT"}

Some benchmarks

Building a tree of N intervals

              user     system      total        real
100       0.000000   0.000000   0.000000 (  0.000143)
1000      0.000000   0.000000   0.000000 (  0.001094)
10000     0.010000   0.000000   0.010000 (  0.011446)
100000    0.110000   0.000000   0.110000 (  0.115025)
1000000   1.390000   0.000000   1.390000 (  1.387665)

Finding matching interval in tree of N intervals

              user     system      total        real
100       0.000000   0.000000   0.000000 (  0.000030)
1000      0.000000   0.000000   0.000000 (  0.000017)
10000     0.000000   0.000000   0.000000 (  0.000025)
100000    0.000000   0.000000   0.000000 (  0.000033)
1000000   0.000000   0.000000   0.000000 (  0.000028)

Finding matching interval in list of N intervals using Array.find

              user     system      total        real
100       0.000000   0.000000   0.000000 (  0.000055)
1000      0.000000   0.000000   0.000000 (  0.000401)
10000     0.010000   0.000000   0.010000 (  0.003971)
100000    0.010000   0.000000   0.010000 (  0.003029)
1000000   0.040000   0.000000   0.040000 (  0.038484)

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

TODO

  1. Fix README typos and grammatical errors (english speaking contributors are welcomed)
  2. Implement C binding for MRI.

LICENSE

Copyright (c) 2012 Alexei Mikhailov

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

segment_tree's People

Contributors

jcoleman avatar take-five avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

segment_tree's Issues

Lookup fails

Hi,

I am an author of Legitbot, it's a library to detect whether a request comes from a valid Web crawler or from some kind of impersonator. I am using "segment_tree" to quickly lookup IPs in a list of Facebook ranges. And we have a problem when looking for a valid IP and getting negative result back: alaz/legitbot#10

I tried to come up with a smaller test case, but frankly it does not look too small. Here I have the full list of Facebook IP ranges, then I'm building a segment tree and the lookup fails:

a = ["69.63.176.0/20", "66.220.144.0/20", "66.220.144.0/21", "69.63.184.0/21", "69.63.176.0/21", "74.119.76.0/22", "69.171.255.0/24", "173.252.64.0/18", "69.171.224.0/19", "69.171.224.0/20", "103.4.96.0/22", "69.63.176.0/24", "173.252.64.0/19", "173.252.70.0/24", "31.13.64.0/18", "31.13.24.0/21", "66.220.152.0/21", "66.220.159.0/24", "69.171.239.0/24", "69.171.240.0/20", "31.13.64.0/19", "31.13.64.0/24", "31.13.65.0/24", "31.13.67.0/24", "31.13.68.0/24", "31.13.69.0/24", "31.13.70.0/24", "31.13.71.0/24", "31.13.72.0/24", "31.13.73.0/24", "31.13.74.0/24", "31.13.75.0/24", "31.13.76.0/24", "31.13.77.0/24", "31.13.96.0/19", "31.13.66.0/24", "173.252.96.0/19", "69.63.178.0/24", "31.13.78.0/24", "31.13.79.0/24", "31.13.80.0/24", "31.13.82.0/24", "31.13.83.0/24", "31.13.84.0/24", "31.13.85.0/24", "31.13.86.0/24", "31.13.87.0/24", "31.13.88.0/24", "31.13.89.0/24", "31.13.90.0/24", "31.13.91.0/24", "31.13.92.0/24", "31.13.93.0/24", "31.13.94.0/24", "31.13.95.0/24", "69.171.253.0/24", "69.63.186.0/24", "31.13.81.0/24", "179.60.192.0/22", "179.60.192.0/24", "179.60.193.0/24", "179.60.194.0/24", "179.60.195.0/24", "185.60.216.0/22", "45.64.40.0/22", "185.60.216.0/24", "185.60.217.0/24", "185.60.218.0/24", "185.60.219.0/24", "129.134.0.0/16", "157.240.0.0/16", "157.240.8.0/24", "157.240.0.0/24", "157.240.1.0/24", "157.240.2.0/24", "157.240.3.0/24", "157.240.4.0/24", "157.240.5.0/24", "157.240.6.0/24", "157.240.7.0/24", "157.240.9.0/24", "157.240.10.0/24", "157.240.16.0/24", "157.240.19.0/24", "157.240.11.0/24", "157.240.12.0/24", "157.240.13.0/24", "157.240.14.0/24", "157.240.15.0/24", "157.240.17.0/24", "157.240.18.0/24", "157.240.20.0/24", "157.240.21.0/24", "157.240.22.0/24", "157.240.23.0/24", "157.240.0.0/17", "69.171.250.0/24", "157.240.24.0/24", "157.240.25.0/24", "199.201.64.0/24", "199.201.65.0/24", "199.201.64.0/22", "204.15.20.0/22", "157.240.192.0/24", "129.134.0.0/17", "157.240.198.0/24"]

irb(main):061:0> ss = SegmentTree.new(a.map {|ip| [IPAddr.new(ip).to_range, true]})
=> SegmentTree(31.13.24.0..204.15.23.255)

irb(main):062:0> ss.find(IPAddr.new('69.171.251.1'))
=> nil

But If I select only some part of ranges from the same list, then lookup in the resulting segment tree succeeds:

irb(main):063:0> s = SegmentTree.new(a.select {|ip| /^69.171/ === ip}.map {|ip| [IPAddr.new(ip).to_range, true]})
=> SegmentTree(69.171.224.0..69.171.255.255)
irb(main):064:0> s.find(IPAddr.new('69.171.251.1'))
=> #<SegmentTree::Segment:0x00007fb4c8211978 @range=#<IPAddr: IPv4:69.171.240.0/255.255.240.0>..#<IPAddr: IPv4:69.171.255.255/255.255.240.0>, @value=true>

The most evident observation is that some ranges overlap and the list is not sorted. I shall appreciate your help on this issue.

Regards,
Alexander.

Optimization

Those 3 lines in matches? method can be VERY slow with large range.

      when left && (low.range.begin..left.range.end).include?(x) then -1
      when segment.range.include?(x) then 0
      when right && (right.range.begin..high.range.end).include?(x) then 1
      else nil

I changed them to

      when left && low.range.begin <= x && x <= left.range.end then -1
      when segment.range.begin <=x && x <= segment.range.end then 0
      when right && right.range.begin <=x && x <= high.range.end then 1
      else nil

and it's much faster.
I can send you a PR if you want to.

Thanks for this gem!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.