Created
September 9, 2013 16:25
-
-
Save mowat27/6498051 to your computer and use it in GitHub Desktop.
First working version on binary chop. May try an OO version next time
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
| require 'rspec-given' | |
| module Chop | |
| def chop(coll, search, i = 0) | |
| return nil if bad_search?(coll, search) | |
| middle = coll.count / 2 | |
| return i if coll.first == search | |
| if coll[middle] <= search | |
| chop(coll[middle..-1], search, i + middle) | |
| else | |
| chop(coll[0..middle], search, i) | |
| end | |
| end | |
| def bad_search?(coll, search) | |
| coll.empty? || coll.size == 1 && coll.first != search | |
| end | |
| end | |
| describe "binary chop" do | |
| include Chop | |
| Then { chop([], :x).nil? } | |
| Then { chop([:a], :a) == 0 } | |
| Then { chop([:a,:b], :b) == 1 } | |
| Then { chop([:a,:b,:c], :c) == 2 } | |
| Then { chop([:a,:b,:c,:d], :d) == 3 } | |
| Then { chop([:a,:b,:c,:d,:e], :e) == 4 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :f) == 5 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :e) == 4 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :d) == 3 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :c) == 2 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :b) == 1 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :a) == 0 } | |
| Then { chop([:a,:b,:c,:d,:e,:f], :x).nil? } | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment