1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>
use math::random;
// Shuffles a slice using [[math::random::]] to provide pseudo-randomness.
export fn shuffle(items: []opaque, itemsz: size, rand: *random::random) void = {
if (len(items) <= 1) {
return;
};
const data = items: *[*]u8;
for (let i = len(items) - 1; i > 0; i -= 1) {
const j = random::u64n(rand, i: u64 + 1): size;
let a = &data[i * itemsz];
let b = &data[j * itemsz];
swap(a, b, itemsz);
};
};
|