-
Notifications
You must be signed in to change notification settings - Fork 170
/
fisher yates shuffle
47 lines (41 loc) · 1022 Bytes
/
fisher yates shuffle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Utility function to swap elements `A[i]` and `A[j]` in an array
void swap(int A[], int i, int j)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
// Function to shuffle an array `A[]` of `n` elements
void shuffle(int A[], int n)
{
// read array from the highest index to lowest
for (int i = n - 1; i >= 1; i--)
{
// generate a random number `j` such that `0 <= j <= i`
int j = rand() % (i + 1);
// swap the current element with the randomly generated index
swap(A, i, j);
}
}
int main(void)
{
int A[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(A) / sizeof(A[0]);
printf("before shuffle:");
for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
// seed for random input
srand(time(NULL));
shuffle(A, n);
printf("after shuffle:");
// print the shuffled array
for (int i = 0; i < n; i++) {
printf("%d ", A[i]);
}
return 0;
}