Skip to content

Instantly share code, notes, and snippets.

@takatoshiono
Created August 21, 2014 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatoshiono/aa6ed0d6c5c74f617e47 to your computer and use it in GitHub Desktop.
Save takatoshiono/aa6ed0d6c5c74f617e47 to your computer and use it in GitHub Desktop.
2つ目は再帰
#!/usr/bin/env ruby
# http://codekata.com/kata/kata02-karate-chop/
require 'test/unit'
def chop(target, values)
index = values.length / 2
return index if values[index] == target
return -1 if index.zero?
if values[index] > target
chop(target, values[0..index - 1])
else
result = chop(target, values[index..values.length - 1])
return -1 if result == -1
index + result
end
end
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(-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
@takatoshiono
Copy link
Author

ひどいコードだけどテストは通る

@takatoshiono
Copy link
Author

ひどすぎて泣きそう

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment