Debian Codegraph @

sort/shuffle.ha

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