summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2016-08-16 20:01:45 -0600
committermo khan <mo@mokhan.ca>2016-08-16 20:01:45 -0600
commit30c9d52e44a460deb9403387b79896cddaaed861 (patch)
tree1627d8ddddd4d3d3db68ff149e250c689fd46ed7
parentdf54bc1321f7e7b03d8d98fd35c8d3ad47a98948 (diff)
chop with a loop.
-rw-r--r--spec/kata/karate_chop_spec.rb18
1 files changed, 17 insertions, 1 deletions
diff --git a/spec/kata/karate_chop_spec.rb b/spec/kata/karate_chop_spec.rb
index 0c9daa6..3b68dd9 100644
--- a/spec/kata/karate_chop_spec.rb
+++ b/spec/kata/karate_chop_spec.rb
@@ -1,7 +1,6 @@
#http://codekata.com/kata/kata02-karate-chop/
require "spec_helper"
-
# Write a binary chop method that takes an integer search target and a sorted array of integers.
# It should return the integer index of the target in the array, or -1 if the target is not in the array.
# The signature will logically be:
@@ -31,6 +30,23 @@ describe "chop" do
end
end
+ def chop(target, items)
+ low = 0
+ high = items.size
+
+ while low < high
+ mid = low + (high-low)/2
+ if items[mid] == target
+ return mid
+ elsif target > items[mid]
+ low = mid + 1
+ else
+ high = mid
+ end
+ end
+ -1
+ end
+
def assert_equal(expected, actual)
expect(actual).to eql(expected)
end