随机选数算法
detail:
1 package cn.edu.buaa.randomSelectAlgo; 2 3 /** 4 * 等概率从n个数中随机选取m个数,概率为m/n。适用于数据能一次全读入的场景. 5 * 6 */ 7 public class Main_RamdomSelectAlgo { 8 static int[] data = { 5, 6, 7, 8, 9, 1, 2, 3, 4 }; 9 static int[] selectCount = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 10 static int loopCount = 1000_000;// 测试次数,为1次时打印结果即为选取结果 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 for (int i = 0; i < loopCount; i++) { 15 randSelect(data, 5); 16 } 17 for (int i = 0; i < selectCount.length; i++) { 18 System.out.print(selectCount[i] + ", "); 19 } 20 } 21 22 static boolean randSelect(int[] data, int selectNum) { 23 int nSize = data.length; 24 if (nSize < selectNum || selectNum < 0) { 25 return false; 26 } 27 for (int i = 0, iSize = nSize; i < iSize; i++) {// 遍历一遍数据 28 double tmpRamNum = Math.random(); 29 if (tmpRamNum <= (double) selectNum / nSize) { 30 // data[i] is selected 31 selectCount[i]++;// 被选数被选次数加1,初始为0 32 selectNum--; 33 } 34 nSize--; 35 } 36 return true; 37 } 38 }
参考资料:http://club.alibabatech.org/article_detail.htm?articleId=2