CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2002
    Posts
    96

    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.

  2. #2
    Join Date
    Jun 2002
    Location
    Vienna, Austria
    Posts
    47
    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

  3. #3
    Join Date
    Apr 2002
    Location
    Boston, MA
    Posts
    40
    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.

  4. #4
    Join Date
    Jun 2002
    Location
    Vienna, Austria
    Posts
    47
    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured