Skip to content

Instantly share code, notes, and snippets.

@marioaquino
Created October 9, 2011 13:13
Show Gist options
  • Save marioaquino/1273667 to your computer and use it in GitHub Desktop.
Save marioaquino/1273667 to your computer and use it in GitHub Desktop.
Binary chop (recursive solution)
require 'test/unit'
def chop(num, arr)
return -1 if arr.empty?
return -1 unless num <= arr.last
return -1 unless num >= arr.first
seek = lambda do |lower, upper|
next_index = (upper - lower) / 2
val = arr[next_index]
return next_index if val == num
return -1 if next_index == 0
return seek.call(next_index, upper + 1) if val < num
seek.call(lower, next_index)
end
seek.call(0, arr.length)
end
class BinaryTest < Test::Unit::TestCase
def test_chop
assert_equal(-1, chop(3, []))
assert_equal(-1, chop(3, [1]))
assert_equal(0, chop(1, [1]))
#
assert_equal(0, chop(1, [1, 3, 5]))
assert_equal(1, chop(3, [1, 3, 5]))
assert_equal(2, chop(5, [1, 3, 5]))
assert_equal(-1, chop(0, [1, 3, 5]))
assert_equal(-1, chop(2, [1, 3, 5]))
assert_equal(-1, chop(4, [1, 3, 5]))
assert_equal(-1, chop(6, [1, 3, 5]))
#
assert_equal(0, chop(1, [1, 3, 5, 7]))
assert_equal(1, chop(3, [1, 3, 5, 7]))
assert_equal(2, chop(5, [1, 3, 5, 7]))
assert_equal(3, chop(7, [1, 3, 5, 7]))
assert_equal(-1, chop(0, [1, 3, 5, 7]))
assert_equal(-1, chop(2, [1, 3, 5, 7]))
assert_equal(-1, chop(4, [1, 3, 5, 7]))
assert_equal(-1, chop(6, [1, 3, 5, 7]))
assert_equal(-1, chop(8, [1, 3, 5, 7]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment