Library contents

Ruby Array#bsearch_index

bsearch_index in find-minimum mode returns the first index where a monotonic boolean predicate becomes true.

A simple example

Array#bsearch_index

  1. Start with Sorted values 1, 3, 5
  2. Do this Find the first value at least 2
  3. Result 3
One is too small. Three is the first value that satisfies the condition.

Syntax

Ruby syntax
index = sorted.bsearch_index { |value| value >= target }
Run this example in Ruby

Save the program as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Find the first threshold that covers a price

A price catalog is already sorted and can contain repeated thresholds. Locate the correct boundary and check what the returned position means when an exact value is absent.

From the programtiers = [10, 20, 20, 40]
First output line1
lesson.rb
tiers = [10, 20, 20, 40]
[20, 50].each do |target|
  index = tiers.bsearch_index { |value| value >= target }
  puts index.nil? ? 'no tier' : index
end
Output
1
no tier

A sorted ascending array makes this predicate monotonic. If every threshold falls below the target, the lookup returns nil.

Ruby documentation for Array#bsearch_index

Advertisements

Locate a numbered tote

A parcel clerk keeps tote numbers in ascending order. Find the specified item in the sorted register. How many smaller entries come before it?

Given4 · 9 · 15 · 22 | seek 15
Worked result2

Find the earliest permit

A permit clerk starts with the smallest valid identifier. Find the specified item in the sorted register. How many smaller entries come before it?

Given3 · 6 · 10 | seek 3
Worked result0