clojure解数学问题

作者: admin 日期: 2017-10-31 14:01:53 人气: - 评论: 0

最近群里有个问题

把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

相关内容

发表评论
更多 网友评论0 条评论)
暂无评论

Copyright © 2012-2014 我的代码板 Inc. 保留所有权利。

页面耗时0.0235秒, 内存占用1.83 MB, 访问数据库13次

闽ICP备15009223号-1