我想用8个元素对一个int数组进行洗牌,但我希望当我洗牌时,数组索引和该索引上的元素不应该相同
我的数组是
int num[]={0,1,2,3,4,5,6,7,8};
Shuffel(num);
int a = num[0]; //a should not be equal to 0
int b = num[1]; //b should not be equal to 1
int c = num[2]; //c should not be equal to 2
int d = num[3]; //d should not be equal to 3
int e = num[4]; //e should not be equal to 4
任何人都可以像这样帮忙洗牌吗?
答案 0 :(得分:0)
public static void main(String[] args) {
int num[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
for (int i : num) {
System.out.print(i + " ");
}
System.out.println();
shuffleArray(num);
for (int i : num) {
System.out.print(i + " ");
}
}
static void shuffleArray(int[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
if (i == index) {
++i;
} else {
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
这肯定适用于您的用例。如果您通常希望避免使用num[i]=i
,请将i == index
替换为ar[i] == index || ar[index] == i
,因此在某些情况下可能会出现无限终止循环。