Skip to content

Instantly share code, notes, and snippets.

@gnab
Created June 22, 2011 06:36
Show Gist options
  • Save gnab/1039600 to your computer and use it in GitHub Desktop.
Save gnab/1039600 to your computer and use it in GitHub Desktop.
Karate Chop Kata in Clojure
(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)
@follesoe
Copy link

Nice :)

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