jackcogdill
jackcogdill

Reputation: 5122

Scramble array in C?

I have a 2d array of coordinates, and I want to iterate through them in a random order. I am using srand so the coordinates will always be randomized the same with the same password. It is a form of security.
How can I scramble go through 2d array using rand()?

Upvotes: 0

Views: 735

Answers (1)

matt
matt

Reputation: 2429

A simple/easy way to do this is to create an array of integers from 0 to n - 1 where n is the length of the first array.

Shuffle this array, and then use the values in it as indices for iteration over the original array.

There's no standard shuffle method in C so use this:

#include <stdlib.h>

/* Arrange the N elements of ARRAY in random order.
   Only effective if N is much smaller than RAND_MAX;
   if this may not be the case, use a better random
   number generator. */
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;
        }
    }
}

Taken from: http://benpfaff.org/writings/clc/shuffle.html

Upvotes: 1

Related Questions