设为首页 加入收藏

TOP

随机子集的Java实现
2014-11-24 02:58:06 来源: 作者: 【 】 浏览:0
Tags:随机 子集 Java 实现

  获取一个集合中指定个数的随机子集(元素不重复)的实现。


  package com.lavasoft.randomset;


  import java.util.*;


  /**


  * 数学集合概念上的随机子集的Java实现研究代码


  *


  * @author leizhimin 2010-5-17 13:25:52


  */


  public class RundomSubsetToolkit {


  public static void main(String[] args) {


  // int[] rs = randomSubset(1, 5000, 300);


  // for (int r : rs) {


  // System.out.println(r);


  // }


  // List list = new ArrayList(10);


  // list.add("a");


  // list.add("b");


  // list.add("c");


  // list.add("d");


  // list.add("e");


  // list.add("f");


  // list.add("g");


  // list.add("h");


  // list.add("i");


  // list.add("j");


  // List rs1 = randomSubset(list, 5);


  // for (Object o : rs1) {


  // System.out.println(o);


  // }


  //


  int[] array = {7, 9, 2, 8, 6, 4, 3};


  int[] rs3 = randomSubset(array, 4);


  for (int i : rs3) {


  System.out.println(i);


  }


  Map map = new HashMap();


  }


  /**


  * 获取某个范围内指定个数的随机自然数子集


  *


  * @param beginIndex 取之范围起


  * @param endIndex 取之范围止


  * @param subCount 子集元素数目


  * @return 自然数子集


  */


  public static int[] randomSubset(final int beginIndex, final int endIndex, final int subCount) {


  if (beginIndex < 0 || endIndex < 1 || subCount < 0 || endIndex - beginIndex < subCount) {


  throw new RuntimeException("获取随机子集的参数不合逻辑!");


  }


  int[] rs = new int[subCount];


  int rescount = endIndex - beginIndex + 1;


  int[] scope = new int[rescount];


  for (int i = beginIndex; i <= endIndex; i++)


  scope[i - beginIndex] = i;


  Random random = new Random();


  for (int i = 0, odd = rescount - 1; i < subCount; i++, odd--) {


  int ranindex = random.nextInt(odd);


  rs[i] = scope[ranindex];


  scope[ranindex] = scope[odd];


  }


  return rs;


  }


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Scooter Framework——简化的Java.. 下一篇Java正则替换一例

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: