79252285

Date: 2024-12-04 18:10:08
Score: 0.5
Natty:
Report link

I have already posted a similar answer in response to a related StackOverflow quesiton.

Generating non-repeating pseudorandom numbers is possible using quadratic prime residue. This algorithm can generate sequences of unique random numbers in O(1) time and memory for each item in the sequence.

In rust, this has been implemented in the rand-unique crate. A usage example:

use rand::OsRng;
use rand_unique::RandomSequenceBuilder;

// initialize a sequence with a random seed
let sequence = RandomSequenceBuilder<u8>::rand(&mut OsRng);

// iterate through the sequence
for i in sequence.into_iter().take(10) {
    println!("{}", i);
}

Disclaimer: I am the author of the rand-unque crate. The crate currently only supports generating unique numbers in integer type ranges (eg. 0-u8::MAX or 0-u64::MAX). If you have a use-case for generating unique numbers in the range of 0-n, raise a Github issue and I can finish off the PR for this change. Thanks!

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Blacklisted phrase (1): StackOverflow
  • Long answer (-0.5):
  • Has code block (-0.5):
Posted by: Liam Gray