最近群里有个问题
把987654321这9个数从大到小顺序排列,添上十丶一号,使结果等于90
刚好在学习clojure就试着用clojure写代码来搜索答案了
clojure的表现力还是很强的,总共写了20来行代码
(ns my-stuff.core
(:gen-class))
(defn convert-tree [tree]
(if (number? tree)
tree
(let [[a b c] tree]
(if (= a +)
(list (convert-tree b) "+" (convert-tree c))
(list (convert-tree b) "-" (convert-tree c))))))
(defn recursion [t c]
(let [l (last t)
p (drop-last 1 t)]
(if (== c 1)
(if (not= 1 (count t))
(if (== 90 (eval t))
(println (flatten (convert-tree t)))))
(let [nc (dec c)
n (+ (* 10 l) nc)
nt (if (== 1 (count t)) (first t) t )]
(recursion (reverse (conj (reverse p) n)) nc)
(recursion (list + nt nc) nc)
(recursion (list - nt nc) nc)))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(recursion (list 9),9))
输出
(98 + 7 + 6 - 54 + 32 + 1)
(98 + 7 - 6 + 5 + 4 + 3 - 21)
(98 + 7 - 6 - 5 - 4 + 3 - 2 - 1)
(98 + 7 - 6 - 5 - 4 - 3 + 2 + 1)
(98 - 7 + 6 - 5 + 4 - 3 - 2 - 1)
(98 - 7 + 6 - 5 - 4 + 3 - 2 + 1)
(98 - 7 - 65 + 43 + 21)
(98 - 7 - 6 + 5 + 4 - 3 - 2 + 1)
(98 - 7 - 6 + 5 - 4 + 3 + 2 - 1)
(98 - 7 - 6 - 5 + 4 + 3 + 2 + 1)
(9 + 8 + 76 + 5 - 4 - 3 - 2 + 1)
(9 + 8 + 76 - 5 + 4 - 3 + 2 - 1)
(9 + 8 + 76 - 5 - 4 + 3 + 2 + 1)
(9 + 8 + 7 + 6 + 54 + 3 + 2 + 1)
(9 + 8 + 7 - 6 + 54 - 3 + 21)
(9 - 8 + 76 + 5 + 4 + 3 + 2 - 1)
clojure交流群里的大神说可以利用clojure.core.logic来解决,继续研究ing