I have a java project done for school. 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.
This code is supposed to shuffle the 9 buttons in different positions.
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).)
EDIT:
You might better understand it if you encapsulate the assignments in a method:
Now, the code will be simpler to follow:
The idea is you
swap()each element in the array with a random index. This random index is chosen randomly from the array, and its index is denoted asrandomNumber.Since you only
swap()items around, you can easily prove that the output array is a permutation of the original.