shuffle 2-dimensional array

Hi,

I found this code for shuffle one-dimensional int array somewhere:

[CODE]void shuffle(int *array, size_t n)
{
if (n > 1) {
size_t i;
for (i = 0; i < n - 1; i++) {
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
}[/CODE]

How can I make change to this function to shuffle 2-dimensional array. This is the declaration of the 2-dimensional array I need to shuffle.

[code]char list[2000][20];[/code]

This array is an array of string (20 char max). I need to shuffle the outer array not the inner one.

Any help would be really appreciated,
Pat

Comments

  • It depends on how you allocated the array. I assume you allocated it dynamically, as a huge array like that generally don't fit in static memory or on the stack.

    If you allocated it as a mangled 1-d array, then you can use the same code. Otherwise, you have to randomize the other dimension as well, inside the for loop, to get the location of the memory that should be swapped.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion