Thread: Obtaining a random object with loops

  1. #1
    Registered User Gnoober's Avatar
    Join Date
    Oct 2002
    Posts
    40

    Question Obtaining a random object with loops

    Lets see if I can phrase this understandably (is that a word?)...

    I have an array of class objects. I want to run through the entire array and choose a random one with a special attribute. I don't think I can explain it with english... must use second language, c++
    Code:
    class Obj{
        int Number;
        int ID;
    };
    
    Obj listOfObj[3]
    
    // Pretend I just set the first 2 of the "listOfObj".Number to 1
    // and the third's Number to 0.
    // and I set each of their ID to their index in the array
    // listOfObj[1].ID = 1 etc...
    
    /*Now I want to collect all of the listOfObj's whose "Number" is equal to 1, and randomly choose one of them*/
    
    //I do not have a clue about how to go about this
    I hope I worded this good enough. Its a difficult question to put into words. Thanks for the help!

  2. #2
    Loop through them all with a for loop. if (Number == 1), increment the total count of acceptable matches, as well as recording the element your at in a lookup table of some sort. An array with size equal to the maximum number of elements scanned through maybe? Using that example do this afterwards:

    UseThisOne( LookupArray[rand() % Total_Matches] );

    Make sure to check if Total_Matches is > 0 though...
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  3. #3
    Registered User Gnoober's Avatar
    Join Date
    Oct 2002
    Posts
    40
    Thats exactly what I tried but it gave me a "Program has encoutered an error", the XP version of illegal operation. Maybe I just did something stupid, I'll try it again. Thanks for the help though.
    - Grady (:

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Telling a shared_ptr not to delete object?
    By TriKri in forum C++ Programming
    Replies: 5
    Last Post: 08-16-2008, 04:26 AM
  2. random to int?
    By psyadam in forum C# Programming
    Replies: 7
    Last Post: 07-22-2008, 08:09 PM
  3. Random number + guessing game trouble
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-08-2007, 03:33 AM
  4. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  5. Testing Random Number Generator
    By Roaring_Tiger in forum C Programming
    Replies: 7
    Last Post: 08-12-2005, 12:48 AM