Skip to content

Instantly share code, notes, and snippets.

@drbr
Created November 29, 2017 07:15
Show Gist options
  • Save drbr/3b7bd877d9f6cb7644ab498988798280 to your computer and use it in GitHub Desktop.
Save drbr/3b7bd877d9f6cb7644ab498988798280 to your computer and use it in GitHub Desktop.
Sometimes I write things in C so I remember how.
#include <stdio.h>
#define ARR_SIZE 9
void swap(int* a, int* b) {
if (a == b) {
return;
}
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
unsigned int randomInt() {
FILE* urandomFile = fopen("/dev/urandom", "r");
unsigned int rand;
fread(&rand, sizeof(rand), 1, urandomFile) ;
fclose(urandomFile);
return rand;
}
void shuffle(int list[], int size) {
for (int i = size - 1; i > 0; i--) {
int swapIndex = rand() % (i + 1);
swap(&list[i], &list[swapIndex]);
}
}
void printArray(int list[], int size) {
for (int i = 0; i < size - 1; i++) {
printf("%d, ", list[i]);
}
printf("%d\n", list[size - 1]);
}
int main() {
unsigned int randSeed = randomInt();
srand(randSeed);
int list[ARR_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < 20; i++) {
shuffle(list, ARR_SIZE);
printArray(list, ARR_SIZE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment