Skip to content
Browse files

Binary chop first commit

  • Loading branch information...
0 parents commit 4b0bc395f0b87bfc4a8bca70899ed6420d6dff75 @srikanthps committed Dec 8, 2009
Showing with 65 additions and 0 deletions.
  1. +43 −0 chop-kata/lib/chop.rb
  2. +22 −0 chop-kata/spec/chop_spec.rb
43 chop-kata/lib/chop.rb
@@ -0,0 +1,43 @@
+def chop_linear(searchMe, array)
+ return -1 if array.empty?
+
+ array.each_with_index do |number, index|
+ return index if number.eql?(searchMe)
+ end
+
+ return -1
+
+end
+
+
+def chop_binary(searchMe, array)
+
+ size = array.size
+ mid_value = array[size/2]
+
+ return -1 if array.empty?
+
+ if (size == 1)
+ return -1 if array[0] != searchMe
+ return 0 if array[0] == searchMe
+ end
+
+ if (size == 2)
+ return 0 if array[0] == searchMe
+ return 1 if array[1] == searchMe
+ return -1 if !array.member?(searchMe)
+ end
+
+ if (searchMe <= mid_value)
+ index = chop_binary(searchMe, array[0..(size/2)])
+ index = 0 + index if index != -1
+ else
+ index = chop_binary(searchMe, array[(size/2 + 1)..size])
+ index = index + (size/2 + 1) if index != -1
+ end
+
+ return index
+end
+
+#alias :chop :chop_linear
+alias :chop :chop_binary
22 chop-kata/spec/chop_spec.rb
@@ -0,0 +1,22 @@
+require 'lib/chop'
+
+describe "Binary Chop" do
+
+ it "chop should return -1 if input array is empty" do
+ chop(1, []).should be_equal -1
+ end
+
+ it "chop should return -1 if input array does not contain specified value" do
+ chop(99, [1,2,3,4,5,6,7,100,101,121,131]).should be_equal -1
+ end
+
+ it "chop should return index if input array contains specified value" do
+ chop(1, [1,2]).should be_equal 0
+ chop(2, [1,2]).should be_equal 1
+ chop(1, [1,2,3,4,5,6,7,100,101,121,131]).should be_equal 0
+ chop(4, [1,2,3,4,5,6,7,100,101,121,131]).should be_equal 3
+ chop(100, [1,2,3,4,5,6,7,100,101,121,131]).should be_equal 7
+ chop(131, [1,2,3,4,5,6,7,100,101,121,131]).should be_equal 10
+ end
+
+end

0 comments on commit 4b0bc39

Please sign in to comment.
Something went wrong with that request. Please try again.