蓄水池抽樣Reservior Sampling

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   檔案   for   ar   

編程珠璣第12章練習題10:

如何從n個對象(可以依次看到這n個對象,但事先不知道n的值)中隨機播放一個?具體說來,如何在事先不知道文字檔行數的情況下讀取檔案,從中隨機播放並輸出一行?

解答:我們總選擇 第1行,並以機率1/2選擇第2行,以機率1/3選擇第3行,依次類推,在這一過程結束時,每一行選中的機率是相等的(都是1/n,其中n是檔案的總行數)

i = 0;while more input lines    with probability 1.0/++i            choice = this input lineprint choice

推廣:

如何從未知或者很大樣本空間隨機地取k個數?

for i=k+1:n   m = random(1,i);  //inclusive   if(m<=k)     swap(array[m],array[i]);end print array[1:k]

 

                       --------------引用http://www.cnblogs.com/HappyAngel/archive/2011/02/07/1949762.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.