Shatadal Das
Shatadal Das

Reputation: 29

How can I generate a random number between a range without repeating a number more than once?

I want to assign a random number to the variable of an object and for objects the random number shouldn't match with the variable of any other object.

I have written the code to generate a random number between a range but it repeats. So, I want a fix.

Upvotes: 1

Views: 148

Answers (1)

miszcz2137
miszcz2137

Reputation: 914

There are multiple solutions depending on the range of the indices that you need.

If it is rather small just generate vector of all values and shuffle it

std::vector<size_t> indices(index_count);
std::iota(indices.begin(), indices.end(), 0);
std::random_shuffle(indices.begin(), indices.end()); // Or std::shuffle with custom RNG.

Next solution is to store the indices generated so far.

std::unordered_set<size_t> indices;
size_t generate(std::unordered_set<size_t>& indices) {
  while (true) {
    size_t index = ...; // Generate a possibly repeating index.
    if (indices.insert(index).second) { // .insert(...).second checks whether the value is new in set.
      return index;
    }
  }
}

The last solution is to use pseudo random number generator that can be mathematically proven to not repeat (until some large number of calls).

Upvotes: 1

Related Questions