我有这样的需求:
我有100道试题,id是0到99,我想从中找出20道试题组成一个试卷,要求试题不重复,打乱顺序:
- /**
- * 产生无重复的随机数 sumInt:总样本 (0....sumInt-1)
- * resultSum: 产生的随机数个数
- *
- * @return
- */
- public static int[] randoms(int sumInt, int resultSum) {
- Random r = new Random();
- int temp1, temp2;
- //Total sample
- int send[] = new int[sumInt];//0....(sumInt-1)
- for (int i = 0; i < sumInt; i++) {
- send[i] = i;
- }
- int len = send.length;//The length of the total sample
- int returnValue[] = new int[resultSum];//Random number to return
- for (int i = 0; i < resultSum; i++) {
- temp1 = Math.abs(r.nextInt()) % len;
- temp2 = send[temp1];
- returnValue[i] = temp2;
- if (temp1 != len - 1) {
- send[temp1] = send[len - 1];
- send[len - 1] = temp2;
- }
- len--;
- }
- return returnValue;
- }
测试:
public static void printArray(int[] ints) {
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i]);
if (i < ints.length - 1) {
System.out.print(" ,");
}
}
System.out.println();
}
@Test
public void test_randoms(){
printArray(SystemUtil.randoms(5, 3));
}