Reputation: 899
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.
Upvotes: 0
Views: 84
Reputation: 178411
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:
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. This random index is chosen randomly from the array, and its index is denoted as randomNumber
.
Since you only swap()
items around, you can easily prove that the output array is a permutation of the original.
Upvotes: 2
Reputation: 14173
for(int i = 0; i< leftbut.length; i++){
Is a loop, it inizialize variable i to 0, and increment it each loop by 1
int randomNumber =(int)(Math.random()*leftbut.length);
declare the integer variable randomNumber and assign a random value in range 0 - length of array
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
Upvotes: 1
Reputation: 1246
It just 9 times randomly swaps to elements of leftbut array.
Upvotes: 1