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?
Asked
Active
Viewed 776 times
-3
-
1Did you have a particular language in mind for this? – Retired Ninja Feb 16 '15 at 22:10
-
Most (pseudo) random number generators have a function for this, just watch the inclusive/exclusive bounds.There is no specific problem/question here. – H H Feb 16 '15 at 22:12
-
C++ is the language of choice – James Garner Feb 16 '15 at 22:14
-
Also: duplicate http://stackoverflow.com/questions/7560114/random-number-c-in-some-range – Diniden Feb 16 '15 at 22:56
1 Answers
-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