Last active
October 13, 2023 08:58
-
-
Save vurtun/29693237182d319fe4cb64bbe155e20b to your computer and use it in GitHub Desktop.
Array shuffle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define xglue(x, y) x##y | |
#define glue(x, y) xglue(x, y) | |
#define uniqid(name) glue(name, __LINE__) | |
#ifdef _MSC_VER | |
#define swap(a,b) do { decltype((a) + 0) _t = (a); (a) = (b); (b) = _t; } while(0) | |
#else | |
#define swap(a,b) do {__typeof__((a) + 0) _t = (a); (a) = (b); (b) = _t; } while(0) | |
#endif | |
static void | |
seq_fix(int *p, int n) { | |
for (int i = 0; i < n; ++i) { | |
p[i] = -1 - p[i]; | |
} | |
} | |
#define arr_shfl(a,n,p) do { \ | |
for (int uniqid(i) = 0; uniqid(i) < n; ++uniqid(i)) { \ | |
if (p[uniqid(i)] >= 0) { \ | |
int uniqid(j) = uniqid(i); \ | |
while (p[uniqid(j)] != uniqid(i)) { \ | |
const int uniqid(d) = p[uniqid(j)]; \ | |
swap(a[uniqid(j)], a[uniqid(d)]); \ | |
p[uniqid(j)] = -1 - uniqid(d); \ | |
uniqid(j) = uniqid(d); \ | |
} p[uniqid(j)] = -1 - p[uniqid(j)]; \ | |
} \ | |
}} while (0) | |
extern int | |
main(void) { | |
int seq[] = {5,4,3,2,1,0}; | |
const char *data[] = { | |
"0.0f", | |
"1.0f", | |
"2.0f", | |
"3.0f", | |
"4.0f", | |
"5.0f", | |
}; | |
arr_shfl(data, 6, seq); | |
for (int i = 0; i < 6; ++i) { | |
printf("%s\n", data[i]); | |
} | |
seq_fix(seq,6); | |
for (int i = 0; i < 6; ++i) { | |
printf("%d\n", seq[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment