Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm Clojure中的随机树遍历_Algorithm_Clojure - Fatal编程技术网

Algorithm Clojure中的随机树遍历

Algorithm Clojure中的随机树遍历,algorithm,clojure,Algorithm,Clojure,给定一棵编码为一组嵌套列表的树,例如+2+2 1+1 3 2,Clojure中是否有一种已知的算法随机遍历该树,在单个节点上应用参数化提供的函数,在任何节点上“着陆”的概率相等?注意:转换单个节点后,漫游将终止 我希望算法的行为如下: (def tree '(1 (1 (1 1 1) 1) 1)) (stochastic-tree-f-app inc tree) => (1 (1 (1 2 1) 1) 1) (stochastic-tree-f-app inc tree) => (1

给定一棵编码为一组嵌套列表的树,例如+2+2 1+1 3 2,Clojure中是否有一种已知的算法随机遍历该树,在单个节点上应用参数化提供的函数,在任何节点上“着陆”的概率相等?注意:转换单个节点后,漫游将终止

我希望算法的行为如下:

(def tree '(1 (1 (1 1 1) 1) 1))
(stochastic-tree-f-app inc tree) => (1 (1 (1 2 1) 1) 1)
(stochastic-tree-f-app inc tree) => (1 (1 (1 1 2) 1) 1)
(stochastic-tree-f-app inc tree) => (2 (1 (1 1 1) 1) 1)
(stochastic-tree-f-app inc tree) => (1 (1 (1 1 1) 1) 2)
(stochastic-tree-f-app dec tree) => (1 (1 (1 1 1) 0) 1)

如果最后一个需求可以取消,那么您可以简单地使用clojure.walk,即…walk在单个节点转换后终止。或者使用拉链沿节点向下走,并以编辑结束。使用clojure.walk:

(use 'clojure.walk)

(def tree '(1 (1 (1 1 1) 1) 1))

(defn stochastic-tree-f-app [f tree]
  (let [cnt (atom 0)
        _   (postwalk #(if (integer? %) (swap! cnt inc)) tree)
        idx (rand-int @cnt)]
    (reset! cnt 0)
    (postwalk #(if (and (integer? %) (= idx (swap! cnt inc)))
                (f %)
                %)
              tree)))

user> (stochastic-tree-f-app inc tree)
(2 (1 (1 1 1) 1) 1)
user> (stochastic-tree-f-app inc tree)
(1 (1 (1 1 1) 2) 1)

如果最后一个需求可以取消,那么您可以简单地使用clojure.walk,即…walk在单个节点转换后终止。或者使用拉链沿节点向下走,并以编辑结束。使用clojure.walk:

(use 'clojure.walk)

(def tree '(1 (1 (1 1 1) 1) 1))

(defn stochastic-tree-f-app [f tree]
  (let [cnt (atom 0)
        _   (postwalk #(if (integer? %) (swap! cnt inc)) tree)
        idx (rand-int @cnt)]
    (reset! cnt 0)
    (postwalk #(if (and (integer? %) (= idx (swap! cnt inc)))
                (f %)
                %)
              tree)))

user> (stochastic-tree-f-app inc tree)
(2 (1 (1 1 1) 1) 1)
user> (stochastic-tree-f-app inc tree)
(1 (1 (1 1 1) 2) 1)
使用:

使用:


因此,一旦你变换了一个节点,行走就结束了,对吗?@Clojuremotly,是的,这是正确的,我想到了一个解决方案:1。按bfs或dfs遍历树,返回节点数2。将该数字馈送到随机整数生成器,将结果馈送到0到n到3之间。第三个d/bfs以随机数生成器4指定的次数遍历图形。我不知道你说的单个节点是什么意思。它是一种类似+2 1的形式吗?还是只有像2这样的值?我们需要排除像+?这样的操作符吗?好问题。我们不排除+之类的运算符。也就是说,我们不局限于像2这样的值。因此,一旦你变换了一个节点,行走就结束了,对吗?@clojuremotly,是的,这是正确的,我想到的解决方案是:1。按bfs或dfs遍历树,返回节点数2。将该数字馈送到随机整数生成器,将结果馈送到0到n到3之间。第三个d/bfs以随机数生成器4指定的次数遍历图形。我不知道你说的单个节点是什么意思。它是一种类似+2 1的形式吗?还是只有像2这样的值?我们需要排除像+?这样的操作符吗?好问题。我们不排除+之类的运算符。也就是说,我们不局限于像2这样的价值观。这是美的这是美的这是更美的这是更美的