Created
February 17, 2016 10:44
-
-
Save sideshowcoder/8d11738a84c3e581b631 to your computer and use it in GitHub Desktop.
1. Solution to http://codekata.com/kata/kata02-karate-chop/
This file contains hidden or 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
| require "pry" | |
| def chop number, numbers, acc = 0 | |
| return -1 if numbers.nil? || numbers.empty? | |
| pivot_pos = (numbers.size / 2) | |
| pivot = numbers[pivot_pos] | |
| return pivot_pos + acc if pivot == number | |
| smaller = numbers.slice(0, pivot_pos) | |
| res = chop(number, smaller, acc) | |
| return res if res != -1 | |
| bigger = numbers.slice(pivot_pos, numbers.size-1) | |
| chop(number, bigger, acc + pivot_pos) | |
| end | |
| require "minitest/autorun" | |
| class Test < Minitest::Test | |
| 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(1, chop(5, [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