Created
August 26, 2014 00:19
-
-
Save takatoshiono/f1dc8748972440b486a5 to your computer and use it in GitHub Desktop.
これも再帰。ちょっと日を置いて書いたらすんなり書けた
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# http://codekata.com/kata/kata02-karate-chop/ | |
require 'test/unit' | |
def chop(target, values) | |
middle = values.length / 2 | |
return -1 if values[middle].nil? | |
return middle if target == values[middle] | |
return -1 if middle == 0 | |
if target < values[middle] | |
index = chop(target, values[0..middle-1]) | |
return index if index != -1 | |
else | |
index = chop(target, values[middle+1..values.length-1]) | |
return middle + 1 + index if index != -1 | |
end | |
-1 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ループと再帰の他にどんな書き方があるか思いつかないなー