Hackerrank Count Swaps
Challenge
Prit’s 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)))
)
I make a nested loop-recur one for iterating through the i index and one for iterating through the j index.