一、从数组中随机抽取若干不重复元素
/**
* @function:从数组中随机抽取若干不重复元素
*
* @param paramArray:被抽取数组
* @param count:抽取元素的个数
* @return:由抽取元素组成的新数组
*/
public static String[] getRandomArray(String[] paramArray,int count){
if(paramArray.length<count){
return paramArray;
}
String[] newArray=new String[count];
Random random= new Random();
int temp=0;//接收产生的随机数
List<Integer> list=new ArrayList<Integer>();
for(int i=1;i<=count;i++){
temp=random.nextInt(paramArray.length);//将产生的随机数作为被抽数组的索引
if(!(list.contains(temp))){
newArray[i-1]=paramArray[temp];
list.add(temp);
}
else{
i--;
}
}
return newArray;
}
二、从list中随机抽取若干不重复元素
/**
* @function:从list中随机抽取若干不重复元素
*
* @param paramList:被抽取list
* @param count:抽取元素的个数
* @return:由抽取元素组成的新list
*/
public static List getRandomList(List paramList,int count){
if(paramList.size()<count){
return paramList;
}
Random random=new Random();
List<Integer> tempList=new ArrayList<Integer>();
List<Object> newList=new ArrayList<Object>();
int temp=0;
for(int i=0;i<count;i++){
temp=random.nextInt(paramList.size());//将产生的随机数作为被抽list的索引
if(!tempList.contains(temp)){
tempList.add(temp);
newList.add(paramList.get(temp));
}
else{
i--;
}
}
return newList;
}
或者如下方法:
思路1:利用List来把数组保存起来,在每取出一个元素后就删除这个元素。
/**
* 使用一个List来保存数组,每次随机取出一个移除一个。
*/
public String[] getRandomArray(int n, String[] strArray){
List<String> list = new ArrayList<String>();
for(int i=0; i<strArray.length; i++){
list.add(strArray[i]);
}
Random random = new Random();
// 当取出的元素个数大于数组的长度时,返回null
if(n>list.size()){
return null;
}
String[] result = new String[n];
for(int i=0; i<n; i++){
// 去一个随机数,随机范围是list的长度
int index = random.nextInt(list.size());
result[i] = list.get(index);
list.remove(index);
}
return result;
}
思路2:在使用一个boolean型数组保存对应数组中元素是否被取出的状态。
/**
* 使用一个两个数组,一个来保存元素,一个用来保存对应元素是否被取走
*/
public String[] getRandomArray(int n, String[] strArray){
// 当取出的元素个数大于数组的长度时,返回null
if(n>strArray.length){
return null;
}
// 定义一个域strArray相同长度的数组,每个位置保存对应位置是否被取走
boolean[] bool = new boolean[strArray.length];
for(int i=0; i<strArray.length; i++){
bool[i] = false;
}
Random random = new Random();
String[] result = new String[n];
for(int i=0; i<n; i++){
int index;
// 判断随机的位置是否被取走,取走则继续循环
do{
index = random.nextInt(n);
}while(bool[index]);
// 取出元素,将其对应位置设置为true
bool[index] = true;
result[i] = strArray[index];
}
return result;
}