如何从树中获取随机节点?

发布于 2024-08-27 19:25:27 字数 193 浏览 6 评论 0原文

看起来很简单,但我发现实现起来很棘手。我需要它来解决我正在尝试实现的简单遗传编程问题。给定一个节点,该函数应该返回该节点本身或其任何子节点,以便选择一个节点的概率相对于其深度呈正态分布(因此该函数应该主要返回中间节点,但有时返回根本身或最低节点)那些 - 但如果这使它变得更加复杂,那么这并不是真正必要的,如果以相同的概率选择所有节点,那就足够了)。

谢谢

It looks easy, but I found the implementation tricky. I need that for a simple genetic programming problem I'm trying to implement. The function should, given a node, return the node itself or any of its children such that the probability of choosing a node is normally distributed relative to its depth (so the function should return mostly middle nodes, but sometimes the root itself or the lowest ones - but that's not really necessary if that makes it significantly more complex, if all any node is chosen with equal probability, that's good enough).

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹淡然 2024-09-03 19:25:27

对于统一情况,如果您知道每个节点的深度,则可以使用概率 size(left)/size(this) 向左移动,使用概率 size(right)/size(this) 向右移动,否则选择当前节点。每个时刻一个随机数就足够了:

int r = rand() % size(this);
if (r < size(left)) { /* go left */ }
else if (r > size(left)) { /* go right */ }
else { /* pick this node */ }

事实上,通过一些调整,您可能可以将一个随机数向下传递以在每个节点上使用。经过一番思考,是的,你可以:如果你向左走,则使用未修改的 r ;如果向右走,则从 r 中减去 (size(left) - 1)

对于正态分布,只需使用平均值为深度一半的正态分布随机变量来提前选择深度,然后回到上述算法。请注意,这将根据其子树的相对大小在中间节点之间分布,而不是均匀分布。

For the uniform case, if you know each node's depth, you could go left with probability size(left)/size(this), right with probability size(right)/size(this), otherwise pick the current node. A single random number at each juncture should suffice:

int r = rand() % size(this);
if (r < size(left)) { /* go left */ }
else if (r > size(left)) { /* go right */ }
else { /* pick this node */ }

In fact, with some adjustments, you can probably pass the one random number down to be used at every node. After some thought, yes you can: if you go left, use r unmodified; if you go right, subtract (size(left) - 1) from r.

For the normal distribution, just use a normally distributed random variable with a mean of half the depth to choose in advance how deep to go, then fall back to the above algorithm. Be warned that this will distribute among the middle nodes according the relative sizes of their subtrees, not uniformly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文