Sha256: eee29a1751ab6db99df225fb208918097b79e8a8c2c6de7bd7ec23a0de73750d

Contents?: true

Size: 1.3 KB

Versions: 32

Compression:

Stored size: 1.3 KB

Contents

unless Range.method_defined? :bsearch
  class Range
    def bsearch
      return to_enum(:bsearch) unless block_given?
      from = self.begin
      to   = self.end
      unless from.is_a?(Numeric) && to.is_a?(Numeric)
        raise TypeError, "can't do binary search for #{from.class}"
      end

      midpoint = nil
      if from.is_a?(Integer) && to.is_a?(Integer)
        convert = Proc.new{ midpoint }
      else
        map = Proc.new do |pk, unpk, nb|
          result, = [nb.abs].pack(pk).unpack(unpk)
          nb < 0 ? -result : result
        end
        from = map['D', 'q', to.to_f]
        to   = map['D', 'q', to.to_f]
        convert = Proc.new{ map['q', 'D', midpoint] }
      end
      to -= 1 if exclude_end?
      satisfied = nil
      while from <= to do
        midpoint = (from + to).div(2)
        result = yield(cur = convert.call)
        case result
        when Numeric
          return cur if result == 0
          result = result < 0
        when true
          satisfied = cur
        when nil, false
          # nothing to do
        else
          raise TypeError, "wrong argument type #{result.class} (must be numeric, true, false or nil)"
        end

        if result
          to = midpoint - 1
        else
          from = midpoint + 1
        end
      end
      satisfied
    end
  end
end

Version data entries

32 entries across 32 versions & 2 rubygems

Version Path
backports-3.6.6 lib/backports/2.0.0/range/bsearch.rb
backports-3.6.5 lib/backports/2.0.0/range/bsearch.rb
backports-3.6.4 lib/backports/2.0.0/range/bsearch.rb
backports-3.6.3 lib/backports/2.0.0/range/bsearch.rb
backports-3.6.2 lib/backports/2.0.0/range/bsearch.rb
backports-3.6.1 lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.5 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.4 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.3 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.3.pre lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.2 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.1 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-1.0.0 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-0.5.5 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-0.5.5.pre lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
scout_realtime-0.5.4 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb
backports-3.6.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.5.0 lib/backports/2.0.0/range/bsearch.rb
backports-3.4.1 lib/backports/2.0.0/range/bsearch.rb
scout_realtime-0.5.3 lib/vendor/backports-3.3.5/lib/backports/2.0.0/range/bsearch.rb