由于最近的排班系统中的需要,写了个这样的类,里面有个方法,用来生成某个某个闭区间内整数的一个随机排列之后数组,拿出来分享一下,有点意思:
import java.util.Random;
public class UniqueArray
{
private static final int RONDOM_TIMES = 100;
public static int[] getRandomArray(int start, int end)//返回某个范围内(闭区间),数值唯一的整数数组
{
int amount = end - start;
int result[] = new int[amount];
for (int i = 0; i < amount; i++)
{
result[i] = start + i;
}
Random rondom = new Random();
int x1 = 1, x2 = 1, temp = 0;// temp是交换时的中转变量
for (int i = 0; i <RONDOM_TIMES; i++)
{
x1 = rondom.nextInt(amount) ;
do{
x2 = rondom.nextInt(amount);
}while (x2 == x1);
//交换
temp = result[x1];
result[x1] = result[x2];
result[x2] = temp;
}
return result;
}
public static int[] getRandomArray(int amount)
{
return UniqueArray.getRandomArray(0,amount-1);
}
}