-3

I am interested in generating a random number between an interval [a b] for a given size; for this, I will move my elements in an array by this random number. For example, if my size is 4 -- I will generate a random number between [-4 and 4] and move my element in array by this number. I know how to generate a number but does anyone know how to do so with this requirement?

Retired Ninja
  • 4,785
  • 3
  • 25
  • 35

1 Answers1

-2

Just did a quick search for Cpp random function: http://www.cplusplus.com/reference/cstdlib/rand/

Thus:

// Assumming size is an int
(rand() % (size*2)) - size
Diniden
  • 1,005
  • 6
  • 14
  • Don't use modulus to limit random numbers: http://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator –  Feb 16 '15 at 23:02
  • The request isn't about getting a crazy perfect randomness. It's ok to write a single line of code if it saves time in readability, understanding, or even performance. The link you referenced has a ridiculous notion to do a do while loop to find a random number as the solution. If you're into heating up a battery for a little better randomness, go for it. Otherwise KISS before you optimize or tune behavior or try to explain to someone who clearly doesn't grasp the basics. – Diniden Feb 16 '15 at 23:07