I have a piece of Clojure code that reverses a string recursively.
It is working but too slow (because I got the problem from Codewars
and I cannot validate it before it timeouts).
The algorithm is :
- take a string ex. "abc" and reverse it (r "abc") -> "cba"
- take the first position and reverse from there "c" + (r "ba") -> "cab"
- take the second position and reverse from there "ca" + (r "b") -> "cab" and so on..
First iteration :
(defn reverse-fun [s]
(loop [r s p 0]
(if (= p (count s))
r
(let [[b e] (split-at p r)
e (reverse e)]
(recur (apply str (concat b e)) (inc p))))))
However it was too slow. I pass about 31 tests with this one before the timeout. Here is the fastest I have for now :
(defn reverse-fun [s]
(apply str (loop [r (vec s) p 0]
(if (= p (count r))
r
(let [b (subvec r 0 p)
e (rseq (subvec r p (count r)))]
(recur (into [] (concat b e)) (inc p)))))))
This code passes about 72 tests before there is a timeout. How can I make this code faster ?