-
Ask about random number
I want to generate random number between 1- 400,000 which is not the same value.
Example.
If X1 = 254899
X2 not have the same value as X1.
and X3 not have the same value as X1 and X2 .
I want to generate data X1 - X400,000 which not have the same value and each data have value between 1-400,000
If you know how to do that, please tell me. Thank you.
-
maybe this helps:
1) create an array (size 400000) and fill it with values from 1 - 400000
2) create a randum number X between 1 and actual array-size
3) return value of array[X] as "real random number"
4) remove the X'th entry from the array
5) continue with 2)
=> you get each value exactly once
=> you have no overhead in finding a "unused" number
-
There's also a way to do it without using variable sized arrays.
1) Create an array of 400,000, say it's called x.
2) For each array value x[i] assign it i +1, x[0] =1, x[1] = 2, x[2] = 3, .... x[399,999]=400,000
3) For each number between 0, and 399,999, pick a random number j (you can use rand() which returns a random double between 0 and 1 and multiply rand, by 400,000)
x[i] swap x[j] (in code: a= x[i]; b=x[j], x[i] = b; x[j]=a;)
4) At this point you'll have a randomly sorted array that has values from 1 -> 400,000. To pick a random number, return x[k], where k goes from 0->399,999 and is increased after a new random number has been returned.
-
you are right mamotron:
resizing the array is bad, but we also can take my solution and swap x[i] with the last unused element instead of deleting it :)