Created
April 21, 2010 18:40
-
-
Save melwin/374222 to your computer and use it in GitHub Desktop.
This file contains 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
def binsearch(ar, v, s=0, e=ar.length) | |
#if we have an empty slice, return nil | |
return nil if s >= e | |
#if we have a slice with one element, return index if it's the value else nil | |
return ar[s] == v ? s : nil if e-s == 1 | |
#get pivot as average of start and end | |
pivot = (e+s) / 2 | |
#search first part if val > pivot, else second | |
return ar[pivot] > v ? binsearch(ar, v, s, pivot) : binsearch(ar, v, pivot, e) | |
end | |
File.open("tests.txt", "r") do |infile| | |
success = 0 | |
failed = 0 | |
while (problem = infile.gets) | |
ar = [] | |
v = Integer(infile.gets) | |
infile.gets #skip in [ | |
line = "" | |
while !(line = infile.gets).match(/^\]\?/) | |
ar << Integer(line) | |
end | |
r = binsearch(ar, v) | |
if (line.match(/yes/) and r and ar[r] == v) or (line.match(/no/) and !r) | |
success += 1 | |
else | |
failed += 1 | |
print "#{problem.strip}: fail\n" | |
end | |
infile.gets #skip empty | |
end | |
print "Success: #{success} Failed: #{failed}\n" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment