Last active
December 19, 2015 06:59
-
-
Save tsnow/5915342 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array | |
def self.find_rec(ary,start,fin,num) | |
return if fin < start | |
center = ((fin + start) / 2) | |
case ary[center] <=> num | |
when 0 then | |
return center | |
when -1 then | |
find_rec(ary,center + 1, fin, num) | |
when 1 then | |
find_rec(ary,start, center - 1, num) | |
end | |
end | |
def find(num) | |
self.class.find_rec(self,0,self.length - 1, num) | |
end | |
end | |
def test_id(ary, num) | |
str = ary.inspect + '.find ' + num.to_s | |
other_str = ary.inspect + '.index ' + num.to_s | |
puts " index:#{'% 5s' % eval(other_str).to_s } find:#{'% 5s' % eval(str)} #{str}" | |
end | |
test_id([1,2,3],2) #1 | |
test_id([1,2,3],3) #2 | |
test_id([1,2,3],1) #0 | |
test_id( [1,2,3,4,5], 2) #1 | |
test_id [0,0,0,0,0,0], 1 #nil | |
test_id [0,0,0,0, 1,2], 0 # nil | |
test_id [0,0,0,0, 1,2], 1 #4, -2 | |
test_id [0,0,0,0, 1,2], 2 #5, -1 | |
test_id [], 0 # nil | |
test_id [1], 0 # nil | |
test_id [1], 1 # 0 | |
=begin | |
ruby binary_search.rb | |
index: 1 find: 1 [1, 2, 3].find 2 | |
index: 2 find: 2 [1, 2, 3].find 3 | |
index: 0 find: 0 [1, 2, 3].find 1 | |
index: 1 find: 1 [1, 2, 3, 4, 5].find 2 | |
index: find: [0, 0, 0, 0, 0, 0].find 1 | |
index: 0 find: 2 [0, 0, 0, 0, 1, 2].find 0 | |
index: 4 find: 4 [0, 0, 0, 0, 1, 2].find 1 | |
index: 5 find: 5 [0, 0, 0, 0, 1, 2].find 2 | |
index: find: [].find 0 | |
index: find: [1].find 0 | |
index: 0 find: 0 [1].find 1 | |
=end |
This is the third program of moderate complexity I've ever written correctly on the first try.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whew. Was only off on the equal elements case. I'm gonna call it a win.