3

Is there an algorithm to generate an array containing all the numbers up to N, while using the rand() function?

The problem is that rand() can return the same number, so I need a trick to avoid that.(Meaning generating the numbers in one go, without using the rand() function more than N time)

Edit: The numbers must be a result of the rand() function. Meaning the array needs to be filled using the rand() function N times. (And not hard writing N numbers and then shuffling them)

Thanks in advance!

Martin
  • 378
  • 2
  • 18
  • Look up Fisher-Yates shuffle. Generate the numbers 1..N; shuffle the array into a random sequence (carefully — there are lots of non-random ways of shuffling the array too). – Jonathan Leffler Jun 09 '18 at 18:06
  • Fill the array with increasing numbers, then swap them around using random index values `0` to `N-1`. – Weather Vane Jun 09 '18 at 18:06
  • @WeatherVane The problem is I need to generate the numbers using the rand() function, and not to hard write them – Martin Jun 09 '18 at 18:07
  • This is a duplicate — hunting! – Jonathan Leffler Jun 09 '18 at 18:07
  • You could also do some research about *sets*. – Some programmer dude Jun 09 '18 at 18:07
  • 1
    You ask for `N` random numbers, for `N` elements, so they can't be random. One if each must be there. It is their sequence which is random. – Weather Vane Jun 09 '18 at 18:08
  • 3
    No; the array must not be filled by calling `rand()`. And using the `rand()` function N times is more or less guaranteed to fail at generating N distinct random numbers. Random number generators will generate repeats; that's what happens with random numbers. You have an array to be populated. You start by populating the array with the values 1..N (or N..1, or you can do it more fancifully, but it won't help). Then you use the random number generator N times to permute the array. This gives you your random sequence of values from 1 to N with no repeats. Trying to do otherwise is pointless. – Jonathan Leffler Jun 09 '18 at 18:20

0 Answers0