File: shuffle.ha

package info (click to toggle)
hare 0.26.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,352 kB
  • sloc: asm: 1,374; makefile: 123; sh: 117; lisp: 101
file content (19 lines) | stat: -rw-r--r-- 507 bytes parent folder | download
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);
	};
};