Skip to main content
Provide sample code
Source Link
TMB
  • 209
  • 1
  • 7

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")

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.

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")
Source Link
TMB
  • 209
  • 1
  • 7

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.