Skip to content

Instantly share code, notes, and snippets.

@okbel
Last active September 9, 2016 15:15
Show Gist options
  • Save okbel/78fa3171e2382d1bff7fa526ec1fd6c4 to your computer and use it in GitHub Desktop.
Save okbel/78fa3171e2382d1bff7fa526ec1fd6c4 to your computer and use it in GitHub Desktop.
Daily Kata # 1 - Get Middle
(defn get-middle [x]
(if (odd? (count x))
(subs x (Math/floor (/ (count x) 2.0)) (+ (Math/floor (/ (count x) 2.0)) 1))
(subs x (- (/ (count x) 2.0) 1)(+ (/ (count x) 2.0) 1))
))
;; Better
(defn is-even [s] (= 0 (mod (count s) 2)))
(defn mid [s] (int (Math/ceil (/ (count s) 2))))
(defn get-middle [s]
(if (is-even s)
(subs s (- (mid s) 1) (+ (mid s) 1))
(subs s (- (mid s) 1) (mid s)))
)
function getMiddle(s) {
var str = s.split(""),index;
if (str.length % 2 === 0) {
index = str.length/ 2;
return str[index-1] + str[index]
} else {
index = Math.floor(str.length/ 2)
return str[index]
}
}
function getMiddle(s)
{
return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment