Jump to content

shuffle 2-dimensional array

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
patkhor

patkhor

    Newbie

  • Members
  • Pip
  • 1 posts
Hi,

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

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;

	}

    }

}

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.

char list[2000][20];

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

#2
CPD

CPD

    Learning Programmer

  • Members
  • PipPipPip
  • 57 posts
I got all excited until I read that all you're doing is shuffling strings. ;) The inefficient way is to swap the strings directly:

void shuffle(char array[][20], 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);

      char t[20];


      strcpy(t, array[j]);

      strcpy(array[j], array[i]);

      strcpy(array[i], t);

    }

  }

}

A much faster method is to use an array of char pointers and swap the pointers. That way the swap is fast, and as an added benefit of retaining the original order of the array:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <time.h>


void shuffle(char **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);

      char *t = array[j];

      array[j] = array[i];

      array[i] = t;

    }

  }

}


int main()

{

  char a[5][20] = {

    "I","want","a","pickle","baby"

  };

  char *b[5];

  int i;


  srand((unsigned)time(NULL));


  for (i = 0; i < 5; i++)

    b[i] = &a[i][0];


  for (i = 0; i < 5; i++)

    printf("%s\n", a[i]);


  printf("\n");

  shuffle(b, 5);


  for (i = 0; i < 5; i++)

    printf("%s\n", b[i]);


  printf("\n");


  for (i = 0; i < 5; i++)

    printf("%s\n", a[i]);


  return 0;

}

Another benefit is that you don't have to specify the size of the second dimension because you can pass an array of pointers instead of an array of arrays. :)