algorithm - Racket 中的随机树

标签 algorithm tree code-generation racket

我正在尝试从 Racket 中的列表创建一棵随机树。

这棵树是由一个运营商列表和一个终端列表组成的。

输出将如下所示:

'(* (+ 2 4) 2)

因此可以使用 eval 函数调用列表。

此外,还应指定最大级别。

所以我的猜测是程序如下所示。

(define (make-tree tree level) ... )

我考虑过使用 map 函数并深入扩展每个级别,但我是 lisp-likes 的新手,所以我发现很难找到我需要的算法。

目前每个运算符只接受两个参数(本质上生成的树是二叉树),但在任何答案中包含如何扩展函数以启用三个或更多参数会很有用。

最佳答案

#lang racket

(define (random-from-list xs)
  (list-ref xs (random (length xs))))

;; A TERMINAL is one if terminal1, terminal2, ...

(define TERMINALS '(0 1 2 3 4 5 6 7 8 9))

(define (random-terminal)
  (random-from-list TERMINALS))

;; An OPERATOR is one of '+ '-, '* '/ .

(define OPERATORS '(+ - * /))

(define (random-operator)
  (random-from-list OPERATORS))

;; A TREE is either
;;      i) a terminal
;; or  ii) (list operator terminal1 terminal2 ... terminalN)

(define (random-tree . ignore)
  (match (random 5)               
    [0 (random-list-tree)]      ; probability 1/5 = 20%
    [_ (random-terminal)]))

(define (random-list-tree)
  (define N (+ 2 (random (+ 3 1)))) ; at least two operands, at most 2+3
  (cons (random-operator) (build-list N random-tree)))

生成特定深度的树:

1. generate a tree T
2. find the depth D of T
3. if the depth D is of the desired depth return T
4. otherwise go to 1.

关于algorithm - Racket 中的随机树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32784083/

相关文章:

java - 在奇数元素之后对 LinkedList 进行排序

python - Python中以自定义方式进行树遍历?

python - python自动生成代码

haskell - 类型类函数调用的 GHC 代码生成

c++ - LRU 缓存 C++ 实现问题

algorithm - 重新安排 session 问题 : Where maximum rearrangement can go upto a value k

C 合并排序段错误

java - 在 SWT/Eclipse RCP 中对基本树进行排序

c - 测试树的圆度?

c++ - 如何在 C++ 汇编代码中查找 VPTR?