Created
June 22, 2011 06:36
-
-
Save gnab/1039600 to your computer and use it in GitHub Desktop.
Karate Chop Kata in Clojure
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
(ns chop (:use clojure.test)) | |
(defn chop [n nums] | |
(loop [nums nums offset 0] | |
(if (empty? nums) | |
-1 | |
(let [i (int (/ (count nums) 2)) x (nth nums i)] | |
(cond | |
(= x n) (+ offset i) | |
(> x n) (recur (take i nums) offset) | |
(< x n) (recur (take-last (- (count nums) (inc i)) nums) (inc i))))))) | |
(deftest chop-test | |
(is (= -1 (chop 3 []))) | |
(is (= -1 (chop 3 [1]))) | |
(is (= 0 (chop 1 [1]))) | |
(is (= 0 (chop 1 [1 3 5]))) | |
(is (= 1 (chop 3 [1 3 5]))) | |
(is (= 2 (chop 5 [1 3 5]))) | |
(is (= -1 (chop 0 [1 3 5]))) | |
(is (= -1 (chop 2 [1 3 5]))) | |
(is (= -1 (chop 4 [1 3 5]))) | |
(is (= -1 (chop 6 [1 3 5]))) | |
(is (= 0 (chop 1 [1 3 5 7]))) | |
(is (= 1 (chop 3 [1 3 5 7]))) | |
(is (= 2 (chop 5 [1 3 5 7]))) | |
(is (= 3 (chop 7 [1 3 5 7]))) | |
(is (= -1 (chop 0 [1 3 5 7]))) | |
(is (= -1 (chop 2 [1 3 5 7]))) | |
(is (= -1 (chop 4 [1 3 5 7]))) | |
(is (= -1 (chop 6 [1 3 5 7]))) | |
(is (= -1 (chop 8 [1 3 5 7]))) | |
) | |
(run-tests) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice :)