Re: [問題] 從0-99999選出一千個不重覆的亂數?

看板Programming作者 (遙遠的旅人)時間14年前 (2010/05/28 10:52), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串6/9 (看更多)
JDK 裡Collection API的程式碼: public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); } else { Object arr[] = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list ListIterator it = list.listIterator(); for (int i=0; i<arr.length; i++) { it.next(); it.set(arr[i]); } } } 開一個List裡面裝int from 0~999999,shuffle過, 然後取前面裡要幾個就幾個。 如果你的取樣空間大到RAM會爆炸,那這個程式也是個不錯的出發點去思考。 -- 我所信仰的科學是一種謙卑的理性,承認自身的無知與渺小才能觀察到世界在我們貧 弱的知覺上留下來的痕跡。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.133.44.37
文章代碼(AID): #1B_o__ul (Programming)
討論串 (同標題文章)
文章代碼(AID): #1B_o__ul (Programming)