Skip to content

Instantly share code, notes, and snippets.

@jtallant
Created September 23, 2012 20:53
Show Gist options
  • Select an option

  • Save jtallant/3773016 to your computer and use it in GitHub Desktop.

Select an option

Save jtallant/3773016 to your computer and use it in GitHub Desktop.
Kata 2
def chop(target, ordered_array)
# Wrap ordered array with an array if it has not been wrapped
ordered_array = [ordered_array, 0] if !ordered_array[0].is_a?(Array)
sub_array = ordered_array[0]
total_sliced_from_left = ordered_array[1]
# no matches found
return -1 if sub_array.empty? || sub_array.size == 1 && sub_array[0] != target
middle = sub_array.size / 2
middle_element = sub_array[middle]
if target == middle_element && sub_array.size == 1
return total_sliced_from_left
end
if middle_element < target
size_before = sub_array.size
sub_array = sub_array[middle + 1..sub_array.size]
size_now = sub_array.size
total_sliced_from_left += size_before - size_now
elsif middle_element == target
size_before = sub_array.size
sub_array = sub_array[middle..sub_array.size]
size_now = sub_array.size
total_sliced_from_left += size_before - size_now
else
sub_array = sub_array[0..middle - 1]
end
ordered_array = [sub_array, total_sliced_from_left]
chop(target, ordered_array)
end
require './kata2.rb'
require 'test/unit'
class TestChop < 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(7, chop(22,[1, 3, 5, 7, 8, 10, 11, 22, 23]))
assert_equal(6, chop(15,[1, 3, 5, 7, 8, 10, 15, 22, 23]))
assert_equal(4, chop(5, [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]))
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