在 Hackerrank 上测试失败但回答正确

Tests failing on Hackerrank but answer correct

我有以下解决方案:

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

对于这个问题: https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting

但是,在 运行 提交问题后,none 的测试通过了。不知道为什么。

在测试了大约一个小时后,我意识到你错在哪里了。即,使用 prn 而不是 print 会在实际文本旁边打印引号字符。这让我感到惊讶,因为我一直认为这两者是可以互换的。如果将 prns 更改为 printlns,应该没问题。

我创建的通过所有测试的最终代码:

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

如果您需要进一步的许可,请告诉我。