2

I have a struct that have 6 members. I want to shuffle the struct so when the user hits the Enter key the struct members randomly prints out like this:

First time:

Member3 - Member1
Member4 - Member6
Member5 - Member2

Second time:

Member1 - Member6
Member3 - Member5
Member2 - Member4

And so on as long as the user hits the Enter kyboard the members shuffle.

This is what I have so far:

 int main(void) {
   struct Members[] = {
    { "Member1", 0, 0, 0},
    { "Member2", 0, 0, 0},
    { "Member3", 0, 0, 0},
    { "Member4", 0, 0, 0},
    { "Member5", 0, 0, 0},
     };

   do
 {


  Shuffle(Members, 6)

  }while(getch() != ESC);
 }

EDIT: Is this a good implementation of Fisher-Yates shuffle?

    static int rand_int(int n)
    {
  int limit = RAND_MAX - RAND_MAX % n;
  int rnd;

  do
  {
    rnd = rand();

  }while(rnd >= limit);

  return rnd % n;
      }

void shuffle(Members *s, int n)
{
int i, j;
Members tmp;

for(i = n - 1; i > 0; i--)
{
    j = rand_int(i + 1);

    tmp = s[j];
    s[j] = s[i];
    s[i] = tmp;

    printf("%s\t - %s\n", s[j], s[i]);
}
}
Erik
  • 1,285
  • 2
  • 12
  • 10

1 Answers1

5

Via wikipedia Fisher Yates Shuffle:

To shuffle an array a of n elements (indexes 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer with 0 ≤ j ≤ i
       exchange a[j] and a[i]

The quirk for you is that you are going to have to reassign each element of each struct during the swap. An easier, and more time-efficient way to accomplish the same thing is the have an array of pointers for swapping purposes

Joel
  • 5,618
  • 1
  • 20
  • 19
  • Thanx for the answer, I will try it. And I will try to use an array of poinsters for the swapping. – Erik Jul 01 '11 at 17:43
  • 1
    Joel, the algorithm is in the question, it's not "the issue". This homework is about figuring out how to implement in C language array element shuffling. Since Erik is array-learning in C, you might want to avoid introducing other referencing mechanisms (pointers). – jpinto3912 Jul 01 '11 at 17:45
  • @jpinto3912 and Joel - Have I implemented the shuffle right? Please see my uppdated question. – Erik Jul 02 '11 at 05:49