【发布时间】:2023-03-08 23:38:01
【问题描述】:
我正在努力解决的任务是基于一个名为骑士之旅的问题和这个 Numberphile 视频:https://www.youtube.com/watch?v=G1m7goLCJDY
基本上,我在这里要做的是编写一个辅助函数,它递归地计算给定图(V,E)中的哈密顿路径。它应该按该路径的顺序返回 V 中的元素列表,如果不存在这样的路径,则返回 nil 。但它只返回路径 P 的空列表。
到目前为止我的尝试(进一步向下):(格式有点奇怪)
(defn- H'
;;
;; "This is the helper function for computing the Hamiltonian path.
;; E is the relation, i.e. the graph, we are looking for a path in.
;; a is the current node.
;; S is the set of nodes we haven't visited yet.
;; P is the path we have traveled so far.
;;
;; H' should return a Hamiltonian path through E
;; that begins with P, then goes through a, and then visits every vertex
;; in the set S.
;; If no such path exists, it should return nil."
;;
[E a S P]
;;
{
:pre [
(not (contains? S a))
(not (contains? (set P) a))
(empty? (intersection S (set P)))
]
:post [
(or (empty? %) (= (set %) (union S (set P) #{a})))
(or (empty? %) (= (count %) (+ (count S) (count P) 1)))
]
}
;; (image-of E a) returns the set of edges leading away from the current vertex
;; MY ATTEMPT:
(if-not (empty? S)
(if (some #(H' E % (disj S %) P) (intersection (image-of E a) S))
(concat P [a])
)
)
)
(defn H
"compute a Hamiltonian path in the graph (V, E); returns a list of the elements in V in the
order of that path, or nil if no such path exists"
[V E]
(some #(H' E % (disj V %) '()) V)
)
我不明白为什么我没有从 H 那里得到任何路径 P 作为回报,只是一个空列表?我是否在错误的条件或类似的情况下终止递归? some-function 的谓词是否表述错误?
如果需要进一步说明或需要更多代码,请告诉我。
【问题讨论】:
-
你不应该在你的函数名中使用单引号
'。删除它并重试,然后更新您的问题。另请参阅此模板项目中的文档资源列表(可能会将您的代码放入现有文件中以尝试运行它):github.com/io-tupelo/clj-template#documentation -
嗯?这个函数有很多问题,但它的名字不是其中之一。
-
该名称是分配中代码框架的一部分,它可以工作并且可以运行。我只是在这里发布了 sn-ps,因为我不想发布代码墙。
标签: math clojure knights-tour