shuffleArray

C

Public Domain

Randomly rearrange the contents of an array

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdlib.h>
#include <string.h>

/* ``shuffleArray(deck, elemSize, len)'' randomly reorganizes an
 * array of `len' items, each `elemSize' bytes in size, located at `deck'.
 * It returns `deck' on success, NULL if an error occurred. */

void* shuffleArray(void* restrict deck, size_t elemSize, size_t len) {
 if (!deck || elemSize < 1 || len < 1) return NULL;
 void* restrict buffer = malloc(elemSize);
 if (!buffer) return NULL;
 for (int i=0; i<len; i++) {
  int bavi = random() % (len-i) + i;
  if (bavi != i) {
   memcpy(buffer, deck + elemSize * i, elemSize);
   memcpy(deck + elemSize * i, deck + elemSize * bavi, elemSize);
   memcpy(deck + elemSize * bavi, buffer, elemSize);
  }
 }
 free(buffer);
 return deck;
}