Android/Java中int数组的随机洗牌
我想洗牌一个包含8个元素的整数数组,但我希望当我洗牌它时,数组索引和该索引上的元素不应该是相同的 我的数组是Android/Java中int数组的随机洗牌,java,android,arrays,Java,Android,Arrays,我想洗牌一个包含8个元素的整数数组,但我希望当我洗牌它时,数组索引和该索引上的元素不应该是相同的 我的数组是 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[
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
有人能帮我洗牌吗
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
,因此在某些情况下可能出现无休止的不终止循环。在您提问之前。@Christian对这个答案的简单修改回答了他的问题。您想说什么,…@user3145373ツ 请在评论之前阅读我的完整问题。。。。我不仅需要shuffeling,还应该基于我=数组[i]