[問題] 隨機從一筆資料中選擇,被選的機率要相等

看板C_and_CPP作者 (1)時間10年前 (2013/11/17 15:05), 編輯推噓1(1010)
留言11則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 問題(Question): 問題原文是: Write a function to randomly select n items from a set with m items(an array of unique integers). Each element must have equal probability of being chosen. Please use rand() function which generate a random number 0 and maximum integer, and suppose srand() has been invoked in advance. function: void RandomSelect(int In[], int m, int Out[], int N) 其實不太了解黃色字部份意思 因此為了簡化問題,我先固定陣列In[]和Out[]的大小,並把In[]內容先預設好 把重點放在綠色字的部份 code: http://codepad.org/yYj8sL3q 但是選出來的資料其實是有可能重複的 (我想過用標記法讓被選過的資料不會再被選到,但這應該不是正解吧!?) 不知道是不是有更好的方法可以保證問題原文所說的呢? 謝謝大家! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 180.176.221.68

11/17 15:14, , 1F
不要重複選或者用 shuffle 的方式?
11/17 15:14, 1F

11/17 15:28, , 2F
請問shuffle是指?
11/17 15:28, 2F

11/17 17:45, , 3F
洗牌 準備一固定大小陣列將內容隨意弄亂 然後依序取出
11/17 17:45, 3F

11/17 19:58, , 4F
謝謝~那shuffle用更多的空間囉..請問有更精妙的方法嗎?
11/17 19:58, 4F

11/17 21:00, , 5F
http://codepad.org/MZFe3dG6 這是shuffle的版本
11/17 21:00, 5F

11/17 21:00, , 6F
不知道這樣寫有沒有好點 @@
11/17 21:00, 6F

11/17 21:03, , 7F
std::uniform_int_distribution 應該會被老師揍XD
11/17 21:03, 7F

11/17 21:05, , 8F
http://ppt.cc/kLZE 可以聽聽這個
11/17 21:05, 8F

11/17 21:22, , 9F

11/17 21:47, , 10F
↑上面有寫錯,更正 → http://codepad.org/HGZcDdyk
11/17 21:47, 10F

11/17 22:08, , 11F
感謝大家協助!!
11/17 22:08, 11F
文章代碼(AID): #1IY6gxZY (C_and_CPP)