• Sign Up
• Login
• API
• FAQ
• Tools
• Archive
daily pastebin goal
74%
SHARE
TWEET

# Untitled

a guest Jan 13th, 2018 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. require 'test/unit'
2.
3. def chop(num, arr)
4.   return -1 if arr.empty?
5.   return -1 unless num <= arr.last
6.   return -1 unless num >= arr.first
7.   seek = lambda do |lower, upper|
8.     next_index = (upper - lower) / 2
9.     val = arr[next_index]
10.     return next_index if val == num
11.     return -1 if next_index == 0
12.     return seek.call(next_index, upper + 1) if val < num
13.     seek.call(lower, next_index)
14.   end
15.   seek.call(0, arr.length)
16. end
17.
18. class BinaryTest < Test::Unit::TestCase
19.   def test_chop
20.     assert_equal(-1, chop(3, []))
21.     assert_equal(-1, chop(3, [1]))
22.     assert_equal(0,  chop(1, [1]))
23.     #
24.     assert_equal(0,  chop(1, [1, 3, 5]))
25.     assert_equal(1,  chop(3, [1, 3, 5]))
26.     assert_equal(2,  chop(5, [1, 3, 5]))
27.     assert_equal(-1, chop(0, [1, 3, 5]))
28.     assert_equal(-1, chop(2, [1, 3, 5]))
29.     assert_equal(-1, chop(4, [1, 3, 5]))
30.     assert_equal(-1, chop(6, [1, 3, 5]))
31.     #
32.     assert_equal(0,  chop(1, [1, 3, 5, 7]))
33.     assert_equal(1,  chop(3, [1, 3, 5, 7]))
34.     assert_equal(2,  chop(5, [1, 3, 5, 7]))
35.     assert_equal(3,  chop(7, [1, 3, 5, 7]))
36.     assert_equal(-1, chop(0, [1, 3, 5, 7]))
37.     assert_equal(-1, chop(2, [1, 3, 5, 7]))
38.     assert_equal(-1, chop(4, [1, 3, 5, 7]))
39.     assert_equal(-1, chop(6, [1, 3, 5, 7]))
40.     assert_equal(-1, chop(8, [1, 3, 5, 7]))
41.   end
42. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top