以下是学习过程中遇到的一种思路,对于老司机来说,可能习以为常;对于我自己是一种新的尝试。故做记录,以便查询。
课题目的是使用Random的方法,从0到a(不包含a)的整数中,随机抽取b个不重复的数字。
正常思路为:“创建并初始化一个长度为b的int数组,使用Random的nextInt()方法抽取第一个数字后放入b中存储;然后抽取第二个数字,遍历数组b,查找是否有重复,如果有,则放弃该数字,重新随机。重复以上过程,直到填满数组b。”
以下方法思路:“创建并初始化一个长度为b的int数组用于存储抽取的数字与上面相同,与此同时,创建一个与a等长的boolean数组charge,初始化默认所有的charge元素为false;该数组的每一个元素,对应a的每一个数字。(数字0对应charge[0],数字1对应charge[1],以次类推)抽取某个数字后,则该数字对应的charge[i]元素置为true;通过该值来判断是否该数字已经被抽取过了。这样可以避免对数组b的遍历来核对是否已经抽取过该数字。
package My;
import java.util.Random;
public class RandomOut
{
public int[] randomOut(int a, int b) // 输入从a个大于等于0的整数中,伪随机抽取b个数字。
{
int[] result = new int[b];
boolean[] charge = new boolean[a]; // 使用一个boolean型变量来判断当前的数字是否已经被随机过了。
// 避免了使用for语句去遍历result数组来判断是否已经包含该数字。
Random ran = new Random();
int count = 0;
while (count < b)
{
int temp = ran.nextInt(a);
if (!(charge[temp]))
{
result[count] = temp;
charge[temp] = true;
count++;
continue;
}
}
return result;
}
public String[] randomOut(String[] a, int b) // 从字符串数组a中,伪随机抽取出其中b个字符串。
{
String[] result = new String[b];
int[] temp = randomOut(a.length, b);
for (int i = 0; i < b; i++)
{
result[i] = a[temp[i]]; // temp[i]是从a.length里面随机抽出的一些位置。
}
return result;
}
public String[] randowOut(String[] a) // 将字符串数组a里面的字符串伪随机打乱排序。
{
String[] result = new String[a.length];
int[] temp = randomOut(a.length, a.length);
for (int i = 0; i < a.length; i++)
{
result[i] = a[temp[i]];
}
return result;
}
// 以上用法可以扩展到自定义类的数组,比如Students[]。
}