Skip to content

Instantly share code, notes, and snippets.

@dyba
Created November 10, 2011 23:58
Show Gist options
  • Select an option

  • Save dyba/1356677 to your computer and use it in GitHub Desktop.

Select an option

Save dyba/1356677 to your computer and use it in GitHub Desktop.
Karate Chop - Take Two
def chop(int, array_of_int)
return -1 if array_of_int.empty?
@max ||= array_of_int.size - 1
@min ||= 0
@mid ||= @max / 2 + @min
return @mid if int == array_of_int[@mid]
return -1 if @mid == @max
if int < array_of_int[@mid]
@max = @mid
else
@min = @mid
end
chop(int, array_of_int)
end
require './karate_chop_2'
require 'test/unit'
class KarateChopTest < Test::Unit::TestCase
def test_chop
assert_equal(-1, chop(3, []))
assert_equal(-1, chop(3, [1]))
assert_equal(0, chop(1, [1]))
assert_equal(0, chop(1, [1, 3, 5]))
assert_equal(1, chop(3, [1, 3, 5]))
assert_equal(2, chop(5, [1, 3, 5]))
assert_equal(-1, chop(0, [1, 3, 5]))
assert_equal(-1, chop(2, [1, 3, 5]))
assert_equal(-1, chop(4, [1, 3, 5]))
assert_equal(-1, chop(6, [1, 3, 5]))
assert_equal(0, chop(1, [1, 3, 5, 7]))
assert_equal(1, chop(3, [1, 3, 5, 7]))
assert_equal(2, chop(5, [1, 3, 5, 7]))
assert_equal(3, chop(7, [1, 3, 5, 7]))
assert_equal(-1, chop(0, [1, 3, 5, 7]))
assert_equal(-1, chop(2, [1, 3, 5, 7]))
assert_equal(-1, chop(4, [1, 3, 5, 7]))
assert_equal(-1, chop(6, [1, 3, 5, 7]))
assert_equal(-1, chop(8, [1, 3, 5, 7]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment