一千个随机选择树的节点

时间:2016-04-29 22:46:16

标签: c algorithm tree probability

我需要编写一个代码,我将节点添加到树中,然后随机选择二元搜索树的元素。所有元素应该具有大约相等的被选择概率。我使用以下节点作为我的树的示例。

               60
               / \
             41   72
            /  \
           23  57
          /  \
         1   32`

从那些节点我用我的函数countT(nodeT *p)计算它们,然后我实现了以下算法/伪代码

function random()
   //returns a random element n = countT
function probability_random_of(int x, int y)
 // get the probability of gettin gvalue x on the nth call of random
  for(i=0;i<1000;i++)
      random()
  probability_of_(x)

我的问题和/或问题是要知道我是否采取了正确的方法,或者我是否过度思考。如果我不正确,请随时指导我正确的解决方案。此外,我有使用二项分布或正态分布的想法。

代码的输出将是,

Probabilities after 1000 random selections are
p(60) = 0.135000
p(41) = 0.135000
p(72) = 0.152000
p(23) = 0.147000
p(57) = 0.156000
p(1) = 0.147000
p(32) = 0.128000

这个输出让我感到烦恼,因为它否定了我之前说过的陈述

  

所有元素都应具有大致相同的被选中概率

这意味着所有元素都应该具有确切的结果。

1 个答案:

答案 0 :(得分:0)

忘记树,这不是真的相关。这段代码应该告诉你随机数在(例如)0到1000(只是我选择的任意最大数值)之间吐出给定数字的频率:

#define MAX_VALUES  1000

int index;
float percentages[MAX_VALUES];
int counts[MAX_VALUES];
int maxiterations = 1000000;
for( index = 0; index < MAX_VALUES; ++index )
{
    counts[index] = 0;
}

// Initialize the generator...
srand((unsigned) time(&t));

// Now test for some number of iterations.
for( index = 0; index < maxiterations; ++index )
{
   int value = rand() % 1000;
   ++counts[value];
}

// At this point, each value of the "count" array should be roughly
// equivalent.  But there's no guarantee that they'll be exactly
// equal.  This will calculate the percentages.
for( index = 0; index < MAX_VALUES; ++index )
{
    percentages[index] = (float)counts[index];
    percentages[index] /= (float)maxiterations;
}

同样,无法保证percentages将完全相同。但他们必须接近,在一个特别小的偏差。 maxiterations的值越高,百分比越接近(理论上)。