2008年5月9日星期五

从指定的数组中随机取n个

import java.util.*;

public class Test
{
public static void main(String[] agrs)
{
   int[] allIdList = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
   int[] randomIdList = new Test().getRandomIdList(allIdList,10);
   for(int randomIdList_index = 0;randomIdList_index < randomIdList.length;randomIdList_index++){
    System.out.println(randomIdList[randomIdList_index]);
   }
}


/**
*
* @author liuzhaochun
* @explain:从指定的数组中随机取count个,返回这个数组
* @datetime:2008-5-9
* @return
* @return int [] 包含随机取的count个值的数组
*/
public int[] getRandomIdList(int[] allIdList,int count){
  
   int[] randomIdList = new int[count];
   int randomIdList_index = 0;
   for(int allIdList_index = allIdList.length - 1; randomIdList_index < count;allIdList_index--,randomIdList_index++){
    int temp_Index = (int)(Math.random() * allIdList_index);
    randomIdList[randomIdList_index] = allIdList[temp_Index];
    allIdList[temp_Index] = allIdList[allIdList_index];
   }
   return randomIdList;
}



}

没有评论:

发表评论