1

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?

Sam Estep
  • 12,974
  • 2
  • 37
  • 75
user4871626
  • 31
  • 2
  • 10

2 Answers2

8

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.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
3

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.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • 1
    This solution may distort the statistical properties of the result. – Toby Speight Jul 02 '15 at 14:18
  • @TobySpeight No it won't, or at least no more so than using % does in general. This is "acceptance/rejection", and is a well-known and mathematically correct technique. – pjs Jul 02 '15 at 15:03