堆的算法枚举数组的排列。维基百科关于该算法的文章称,Robert Sedgewick 得出结论,该算法是“当时通过计算机生成排列的最有效算法”,因此尝试实施自然会很有趣。
该算法是关于在可变数组中进行连续交换,所以我正在考虑在 Clojure 中实现它,它的序列是不可变的。我将以下内容放在一起,完全避免了可变性:
(defn swap [a i j]
(assoc a j (a i) i (a j)))
(defn generate-permutations [v n]
(if (zero? n)
();(println (apply str a));Comment out to time just the code, not the print
(loop [i 0 a v]
(if (<= i n)
(do
(generate-permutations a (dec n))
(recur (inc i) (swap a (if (even? n) i 0) n)))))))
(if (not= (count *command-line-args*) 1)
(do (println "Exactly one argument is required") (System/exit 1))
(let [word (-> *command-line-args* first vec)]
(time (generate-permutations word (dec (count word))))))
对于 11 个字符的输入字符串,算法在 7.3 秒内(在我的计算机上)运行(平均超过 10 次运行)。
使用字符数组的等效 Java 程序在 0.24 秒内运行。
所以我想让 Clojure 代码更快。我使用了带有类型提示的 Java 数组。这是我尝试过的:
(defn generate-permutations [^chars a n]
(if (zero? n)
();(println (apply str a))
(doseq [i (range 0 (inc n))]
(generate-permutations a (dec n))
(let [j (if (even? n) i 0) oldn (aget a n) oldj (aget a j)]
(aset-char a n oldj) (aset-char a j oldn)))))
(if (not= (count *command-line-args*) 1)
(do
(println "Exactly one argument is required")
(System/exit 1))
(let [word (-> *command-line-args* first vec char-array)]
(time (generate-permutations word (dec (count word))))))
嗯,它比较慢。现在,11 个字符的数组平均需要 9.1 秒(即使有类型提示)。
我知道可变数组不是 Clojure 的方式,但是有什么方法可以接近 Java 的这种算法的性能吗?