I have the following solution:
(defn count-swaps [a]
(letfn [(swap [a i j] ;; looked up letfn online
(assoc a i (nth a j) j (nth a i)))]
(loop [a a num-swaps 0 i 0]
(if (< i (count a))
(let [int-loop (loop [a' a j 0 num-swaps' 0]
(if (< j (dec (count a)))
(if (> (nth a j) (nth a (inc j)))
(recur (swap a' j (inc j)) (inc j) (inc num-swaps'))
(recur a' (inc j) num-swaps'))
[a' num-swaps']))]
(recur (nth int-loop 0) (+ num-swaps (nth int-loop 1)) (inc i)))
[num-swaps (nth a 0) (nth a (dec (count a)))]))))
(let [result (count-swaps [4 2 3 1])]
(prn (str "Array is sorted in " (nth result 0) " swaps.") )
(prn (str "First Element: " (nth result 1)) )
(prn (str "Last Element: " (nth result 2)))
)
For this problem: https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
However, upon running submitting the problem, none of the tests pass. I don't know why.
after testing this for about an hour or so, I realized where you're mistaken. Namely, using prn
instead of print
prints out the quote characters alongside the actual text. This was a surprise to me, since I always thought that these two are interchangeable. If you change your prn
s to println
s, you should be okay.
The final code that I created which passed all of the tests:
;
; Complete the 'countSwaps' function below.
;
; The function accepts INTEGER_ARRAY a as parameter.
;
(defn count-swaps [a]
(letfn [(swap [a i j] ;; looked up letfn online
(assoc a i (nth a j) j (nth a i)))]
(let [result (loop [a a num-swaps 0 i 0]
(if (< i (count a))
(let [int-loop (loop [a' a j 0 num-swaps' 0]
(if (< j (dec (count a)))
(if (> (nth a j) (nth a (inc j)))
(recur (swap a' j (inc j)) (inc j) (inc num-swaps'))
(recur a' (inc j) num-swaps'))
[a' num-swaps']))]
(recur (nth int-loop 0) (+ num-swaps (nth int-loop 1)) (inc i)))
[num-swaps (nth a 0) (nth a (dec (count a)))]))]
(println (str "Array is sorted in " (nth result 0) " swaps.") )
(println (str "First Element: " (nth result 1)))
(println (str "Last Element: " (nth result 2))))))
(def n (Integer/parseInt (clojure.string/trim (read-line))))
(def a (vec (map #(Integer/parseInt %) (clojure.string/split (clojure.string/trimr (read-line)) #" "))))
(count-swaps a)
Let me know if you need any further clearance on this.