The follow code should correctly run the test cases at the bottom.
It works correctly. I just don't feel like this is clearest way I could write it.
A lot of the complexity comes from having to return the middle two characters if the length of the string is even.
Here is a link to the Programing Challenge.
(defn convert-to-zero-based-list [index]
(- index 1))
(defn convert-to-one-based-list [index]
(+ index 1))
(defn get-middle-with-offset [s]
(/ (convert-to-one-based-list (count s)) 2))
(defn get-start-of-middle [s]
(convert-to-zero-based-list (Math/floor (get-middle-with-offset s))))
(defn get-end-of-middle [s]
(Math/ceil (get-middle-with-offset s)))
(defn get-middle [s]
(subs s (get-start-of-middle s) (get-end-of-middle s)))
(= (get-middle "a") "a")
(= (get-middle "aa") "aa")
(= (get-middle "aba") "b")
(= (get-middle "abba") "bb")
(= (get-middle "abcba") "c")
An alternative would be to recursively/iteratively trim off the first and last elements of the string until you reached the middle one or two characters.
(defn trim-first-and-last [s]
(subs s 1 (dec (count s)))
)
(defn get-middle-recur [s]
(if (<= (count s) 2)
s
(get-middle-recur (trim-first-and-last s))
)
)
(= (get-middle-recur "a") "a")
(= (get-middle-recur "aa") "aa")
(= (get-middle-recur "aba") "b")
(= (get-middle-recur "abba") "bb")
(= (get-middle-recur "abcba") "c")
(= (get-middle-recur "abccba") "cc")