Skip to content

Instantly share code, notes, and snippets.

@brabect1
Created October 11, 2016 10:40
Show Gist options
  • Save brabect1/15b7614053e8c462c8df96f599ac6826 to your computer and use it in GitHub Desktop.
Save brabect1/15b7614053e8c462c8df96f599ac6826 to your computer and use it in GitHub Desktop.
Shows how to randomize a queue or a dynamic array with unique elements.

The following code shows how to randomize a queue. The use of unique is obvious, but the trick is in using size as a constraint, which lets one to control how many elements will be randomized.

int q[$];
...
q.delete();
assert(
    std::randomize( q ) with {
        unique{q};
        q.size == requested_size;
        foreach(q[i]) ...element constraint...;
    }
);

It may be also handy to sort or randomize the order of queue/array elements. Note, though, that the ordering affects the array itself, rather than returning a new, derived queue/array.

q.sort();    // sort
q.shuffle(); // random order of elements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment