Skip to content

nanorand::gen::RandomRange::random_range(lower, upper) behaves incorrectly (upper is non-inclusive) #21

@spitfire05

Description

@spitfire05

WyRand::new().generate_range::<u32>(0, 1); seems to always return 0, while the common understanding is that the upper parameter should be inclusive.

This seems to be the understanding of the crate's author as well, as in shuffle implementation:

fn shuffle<I, S: AsMut<[I]>>(&mut self, mut target: S) {
		let target = target.as_mut();
		let target_len = target.len();
		for idx in 0..target_len {
			let random_idx = self.generate_range::<usize>(0, target_len - 1);
			target.swap(idx, random_idx);
		}
	}

target_len - 1 basically means the last value in slice will never be selected as swap target, leading to some bizarre behavior, like shuffling a slice of len 2 always returns reversed slice, instead of giving roughly 50/50 distribution of original and reversed.

If the upper parameter was indeed meant to be non-inclusive, then I guess the docs should be updated and shuffle implementation fixed. If it was not, then the generate_range function has to be fixed.

Tested on crate v 0.5.2, Rust 1.48.0

EDIT: typos, formatting

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions