user4871626
user4871626

Reputation: 31

exclude one number from a random range

I want to generate a random number from a specific range in each iteration

for (int i = 0; i < 10; i++)
{
    v1[i] = rand() % n;
}

This code will generate a number between 0 and 9. However, I do not want the selected number to be the same as the index i. For example, if I am in the first iteration (ie: i == 1), I want the random number to be either 0, 2, 3, 4, 5, 6, 7, 8, 9 and not 1.

Can someone help me in this?

Upvotes: 1

Views: 2157

Answers (2)

fredoverflow
fredoverflow

Reputation: 263270

If you want to exclude one number, just remove the greatest number from the set of possible choices, and if you happen to pick the one you didn't want, choose the greatest number instead.

For example, if you want to pick a number between 0 and 9, but it should not be the number 1, then pick a number between 0 and 8. If you pick 1, choose 9 instead.

Upvotes: 8

rossum
rossum

Reputation: 15693

Try something like:

for (int i = 0; i < 10; i++)
{
  do
  {
    v1[i] = rand() % n;
  } while (v1[i] == i);
}

Given the numbers you are using the do-loop will only cycle more than once about every ten calls.

Upvotes: 3

Related Questions