I have been trying, with no success, to perform a partial fisher-yates shuffle directly for the first N elements of a 2D array. I know I could transform the 2D array into a 1D array, perform the shuffle and then turn it back, but if possible I would like to avoid this.
The problem in my implementation is, I think although I have not proved it, that the last elements of each row of my array are not correctly shuffled. In fact, supposingI have a m*n array,of which the first N are equal to 1 and the rest m*n - N are equal to 0. When I perform my shuffle of the first N elements of the array, about 67% of the time the elements at the end of each row: array[i][end] are equal to 1, which seems to me to be too many times.
Here is my implementation:
void fisher_yates_shuffle(int n, int nbLines, int nbColumns, int **a)
{
for (int i = 0; i < nbLines; i++)
{
for (int j = 0; j < nbColumns; j++)
{
swap(a, i, j, i+rand()%(nbLines-i), j+rand()%(nbColumns -j)); // swap element with random later element
n--;
if(n<=0)
break;
}
}
}
I know it doesn't look very good and there must be a more efficient way of doing it. Maybe there is a different, equally efficient algorithm to shuffle the first N elements of a 2D array like that?
Aucun commentaire:
Enregistrer un commentaire