[英]How does it works? Shuffling Array
I am trying to understand shuffling arrays in java.我想了解在 java 中改组 arrays。 I do understand how it works
我明白它是如何工作的
for(int i=myList.length-1; i>0; i--) {
int j = (int) (Math.random() * i +1);
double temp = myList[i];
myList[i]=myList[j];
myList[j]=temp;
System.out.print(myList[i]);
but I am lil confused about this part但我对这部分很困惑
int j = (int) (Math.random() * i +1);
it can create same numbers for ex:它可以为 ex 创建相同的数字:
122512111 122512111
So how it works and swaps indexes if it has same numbers.那么如果它具有相同的数字,它是如何工作和交换索引的。
Your code is fine, no need to worry.你的代码很好,不用担心。
Here I try to explain you int j = (int) (Math.random() * i +1);
这里我试着解释一下
int j = (int) (Math.random() * i +1);
in individual part:在个别部分:
Math.random()
:-> gives you random number in float
between 0 to 1. Math.random()
:-> 为您提供介于 0 到 1 之间的float
随机数。
Math.random() * i
:-> multiply with i(index)
so number don't stay in between range 0 to 1
and range will become 0 to myList.length-2
Math.random() * i
:-> 与i(index)
相乘,因此数字不会停留在0 to 1
之间,范围将变为0 to myList.length-2
(Math.random() * i +1)
:-> increment our random number with 1, so range will become 0 to myList.length-1
(Math.random() * i +1)
:-> 将我们的随机数增加 1,因此范围将变为0 to myList.length-1
(int) (Math.random() * i +1);
:-> convert our number from float
to int
:-> 将我们的数字从
float
转换为int
**all above range is inclusive of the start and end number:) **以上所有范围都包括开始和结束号码:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.