簡體   English   中英

樹節點的一千個隨機選擇

[英]One thousand random selections of a Tree's node

我需要編寫一個代碼,將節點添加到樹中,然后隨機選擇二叉搜索樹的一個元素。 所有元素被選中的概率應該大致相等。 我使用以下節點作為我的樹的示例。

               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

這個輸出讓我很煩惱,因為它否定了我之前說過的陳述

所有元素都應該有大致相等的被選中概率

這意味着所有元素都應該有確切的結果。

忘記樹吧,那不是真的相關。 這段代碼應該告訴你隨機數多頻繁地吐出(例如)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的值maxiterations ,百分比應該(理論上)越接近。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM