I’m looking for a function in ANSI C that would randomize an array just like PHP’s shuffle() does. Is there such a function or do I have to write it on my own? And if I have to write it on my own, what’s the best/most performant way to do it?
My ideas so far:
- Iterate through the array for, say, 100 times and exchange a random index with another random index
- Create a new array and fill it with random indices from the first one checking each time if the index is already taken (performance = 0 complexity = serious)
Pasted from Asmodiel‘s link to Ben Pfaff’s Writings, for persistence:
EDIT: And here’s a generic version that works for any type (
int,struct, …) throughmemcpy. With an example program to run, it requires VLAs, not every compiler supports this so you might want to change that tomalloc(which will perform badly) or a static buffer large enough to accommodate any type you throw at it: