Sha256: 2a405ae46da1cbb853c31d87f4f0da1b9c9c8aeb90dcb77bc5ce2a300e5c538b

Contents?: true

Size: 1.76 KB

Versions: 17

Compression:

Stored size: 1.76 KB

Contents

class Bin < Range
  attr_accessor :data

  def initialize(*args)
    super(*args)
    @data = []
  end

  def inspect
    "<(" + super + ") @data=#{data.inspect}>"
  end

  def <<(val)
    @data << val
  end

  # O(m + n) speed to bin objects.
  # bin objects must respond to === .
  # the object to bin must be a value that is sortable (< > ==), or you can
  # pass in a block to get the value.
  # bins and objects must be accessible by index (e.g., bins[11]).
  # if data_capture is given, it should be a parallel array to bins, and each
  # object should respond to the '<<' method.  Otherwise, the bins themselves
  # will be used to push data onto.
  #
  # Here's a simple example of binning x,y points where we want to bin the
  # points based on the x value:
  #
  #     bins = (0...10).map {|i| Bin.new(i, i+1, false) }
  #     points = [[2.2, 100], [3.5, 200], [8.8, 150]]
  #
  #     Bin.bin!(bins, points) {|point| point.first }
  #     # --or--:     Bin.bin!(bins, points, &:first)
  #
  # An example where we want to use a separate data store:
  #
  #
  def self.bin(bins, objects, *data_capture_obj, &block)
    obj_e = objects.each ; obj = obj_e.next  

    data_capture = data_capture_obj.first || bins

    bin_i = 0  # the bin index
    cbin = bins[bin_i]  # the current bin
    done = false
    until done
      value = (block.nil? ? obj : block.call(obj))
      if cbin.begin <= value
        until cbin === value && data_capture[bin_i] << obj
          bin_i += 1
          cbin=bins[bin_i] || (done=true && break)
        end
        obj=obj_e.next rescue done=true
      else
        while cbin.begin > value && !done
          obj=obj_e.next rescue done=true && break
          value = (block.nil? ? obj : block.call(obj))
        end
      end
    end
    data_capture
  end

end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
mspire-0.7.5 lib/bin.rb
mspire-0.7.4 lib/bin.rb
mspire-0.7.3 lib/bin.rb
mspire-0.7.2 lib/bin.rb
mspire-0.6.26 lib/bin.rb
mspire-0.6.25 lib/bin.rb
mspire-0.6.24 lib/bin.rb
mspire-0.6.22 lib/bin.rb
mspire-0.6.21 lib/bin.rb
mspire-0.6.20 lib/bin.rb
mspire-0.6.19 lib/bin.rb
mspire-0.6.18 lib/bin.rb
mspire-0.6.12 lib/bin.rb
mspire-0.6.11 lib/bin.rb
mspire-0.6.9 lib/bin.rb
mspire-0.6.7 lib/bin.rb
mspire-0.6.6 lib/bin.rb