Last active
April 11, 2024 15:21
-
-
Save a2ikm/3e0c00ce71962d56986214391015f7f2 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
# Search who cause the test function succeed from candidates | |
# | |
# @param [Array<T>] array of candidates | |
# @param [(Array<T>) -> bool] lambda function to test subset of candidates | |
# @return [T] last survivor against test function | |
def bisection_search(candidates, test) | |
loop do | |
head = candidates[0...candidates.length/2] | |
tail = candidates - head | |
head_ok = test.call(head) | |
tail_ok = test.call(tail) | |
if head_ok && tail_ok | |
raise <<~EOM | |
both targets succeeded | |
A = #{head} | |
B = #{tail} | |
EOM | |
elsif head_ok | |
if head.length == 1 | |
return head.first | |
else | |
candidates = head | |
end | |
elsif tail_ok | |
if tail.length == 1 | |
return tail.first | |
else | |
candidates = tail | |
end | |
else | |
raise <<~EOM | |
both targets failed | |
A = #{head} | |
B = #{tail} | |
EOM | |
end | |
end | |
end | |
if __FILE__ == $0 | |
candidates = (0...100).to_a | |
p bisection_search(candidates, lambda { |subcandidates| subcandidates.include?(42) }) == 42 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment