CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Random numbers

  1. #1
    Join Date
    Mar 2007
    Posts
    45

    Random numbers

    Hello,

    Im working on a particle system, where i need to calculate the same random numbers from a given id, each time. The ids are given in order of the birth sequence.

    So

    Particle 1.ID = 0
    Particle 2.ID = 1
    Particle 3.ID = 2
    Particle 4.ID = 3

    etc etc

    The way i want it to work is that as Particle 1 is passed through a node, say a position node, the same random Vector3 number is produced each time as long as the ID stays the same. With the Vector3 being made up of XY and Z floating point numbers.

    something like this

    Vector3 getRandomPosition( Int ID );

    and i also want the same for other nodes as well, such as

    Vector3 getRandomPosition( Int ID );
    Vector3 getRandomDirection( Int ID );
    Vector3 getRandomSpeed( Int ID );


    But i dont know how to go about doing this. My first thought was to map the ID range to the floating pointing range of -1 to 1;

    so

    0 - rand_max
    -1 - 1

    and then just assign a rand() for the ID. But this doesnt work, as if i do the same for speed, and direction. The case forms where lower ids, have lower, speed, direction and position values. which looks very obvious.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Random numbers

    Well, technically it's only random the first time you see an ID, right? After that it's deterministic, if I'm understanding properly.

    What I'd do is use a std::map<int, Vector3> chosenPosition, and then do
    Code:
    Vector3 getRandomPosition( int ID )
    {
        return chosenPosition.insert(make_pair(ID, generateRandomVector3())).first->second;
    }
    each time, since insert() will only succeed if the given ID is not already known:
    http://www.cppreference.com/wiki/stl/map/insert

    (Alternatively you could check to see if the ID exists and then only bother generating the random vector if not.....this is really only better if random generation is expensive, however.)
    Last edited by Lindley; April 27th, 2009 at 01:09 PM.

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)