简体   繁体   English

请帮助我理解这段代码

[英]Please help me understand this piece of code

I have a java project done for school. 我有一个为学校完成的Java项目。 This is a piece of code which i am having a hard time to understand its logic. 这是一段代码,我很难理解它的逻辑。 Please shed some light on it. 请阐明一下。

for(int i = 0; i< leftbut.length; i++){
          int randomNumber =(int)(Math.random()*leftbut.length);
             tempNum = leftbut[randomNumber];
            leftbut[randomNumber] = leftbut[i];
            leftbut[i]=tempNum;      

     }

The leftbut in this case is actually an array of 9 buttons. 在这种情况下,左侧按钮实际上是9个按钮的数组。 This code is supposed to shuffle the 9 buttons in different positions. 该代码应该在9个按钮的不同位置进行混洗。 I just cant understand how this code works. 我只是不明白这段代码是如何工作的。

The code generate a random permutation of the original array. 该代码生成原始数组的随机排列

However, note that this is biased - it does not generate all permutations in uniform distribution. 但是,请注意,这是有偏见的-它不会以均匀分布生成所有排列。 This thread discusses what is the affect of this bias. 该主题讨论了这种偏见的影响。

To overcome this issue - you might want to have a look on fisher yates shuffle (which main difference is, to generate a random number in range [i,n) in each iteration instead of in range [0,n).) 为了解决这个问题,您可能需要看一下费舍尔·耶茨的混洗 (主要区别是,在每次迭代中都将生成范围为[i,n]的随机数,而不是范围为[0,n]。)


EDIT: 编辑:
You might better understand it if you encapsulate the assignments in a method: 如果将分配封装在方法中,则可能会更好地理解它:

private static void swap(int[] array, int i, int j) { 
       tempNum = array[j];
       array[j] = array[i];
       array[i]=tempNum; 
}

Now, the code will be simpler to follow: 现在,代码将变得更简单:

for(int i = 0; i< leftbut.length; i++) {
          //choose a random index in the array
          int randomNumber =(int)(Math.random()*leftbut.length);
          //swap the element in index i with the random element chosen in the array
          swap(leftbut, i, randomNumber);
}

The idea is you swap() each element in the array with a random index. 这个想法是您用随机索引对数组中的每个元素进行swap() This random index is chosen randomly from the array, and its index is denoted as randomNumber . 从数组中随机选择此随机索引,其索引表示为randomNumber
Since you only swap() items around, you can easily prove that the output array is a permutation of the original. 由于只swap()周围的项目,因此可以轻松证明输出数组是原始数组的置换。

它仅9次随机交换为leftbut数组的元素。

for(int i = 0; i< leftbut.length; i++){

Is a loop, it inizialize variable i to 0, and increment it each loop by 1 是一个循环,它将变量i初始化为0,并在每个循环中将其递增1

int randomNumber =(int)(Math.random()*leftbut.length);

declare the integer variable randomNumber and assign a random value in range 0 - length of array 声明整数变量randomNumber并分配范围为0的随机值-数组长度

 tempNum = leftbut[randomNumber];         
 leftbut[randomNumber] = leftbut[i];
 leftbut[i]=tempNum;  

this actually invert the 2 buttons position in the array, the value i become the random one and viceversa 这实际上反转了数组中2个按钮的位置,值i变为随机值1,反之亦然

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM