mRandomSet.h

Engine/source/math/mRandomSet.h

More...

Classes:

Detailed Description

 1
 2//-----------------------------------------------------------------------------
 3// Copyright (c) 2012 GarageGames, LLC
 4//
 5// Permission is hereby granted, free of charge, to any person obtaining a copy
 6// of this software and associated documentation files (the "Software"), to
 7// deal in the Software without restriction, including without limitation the
 8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22//-----------------------------------------------------------------------------
23
24#ifndef _MRANDOMSET_H_
25#define _MRANDOMSET_H_
26
27#ifndef _MRANDOM_H_
28#include "math/mRandom.h"
29#endif
30
31template <class T>
32class MRandomSet
33{
34protected:
35
36   MRandomLCG *mRandGen;
37
38   Vector<T> mItems;
39   Vector<F32> mProbability;
40   F32 mSum;
41
42public:
43
44   MRandomSet( MRandomLCG *randGen = &gRandGen );
45
46   void add( const T &item, F32 probability );
47   
48   /// Return a random item from the set using the specified per
49   /// item probability distribution.
50   T get();
51};
52
53template<class T>
54inline MRandomSet<T>::MRandomSet( MRandomLCG *randGen )
55 : mRandGen( randGen ),
56   mSum( 0.0f )
57{
58}
59
60template<class T> 
61inline void MRandomSet<T>::add( const T &item, F32 probability )
62{
63   AssertFatal( probability > 0.0f, "MRandomDeck - item probability must be positive." );
64
65   mItems.push_back( item );
66   mProbability.push_back( probability );
67   mSum += probability;
68}
69
70template<class T> 
71inline T MRandomSet<T>::get()
72{ 
73   AssertFatal( mSum > 0.0f, "MRandomDeck - no items to get." );
74
75   F32 rand = mRandGen->randF(0.0f, mSum);
76
77   F32 prev = -1.0f;
78   F32 curr = 0.0f;
79
80   for ( S32 i = 0; i < mItems.size(); i++ )
81   {
82      curr += mProbability[i];
83
84      if ( rand > prev && rand <= curr )
85         return mItems[i];
86         
87      prev = curr;
88   }
89   
90   AssertFatal( false, "MRandomSet::get() has failed." );
91   return NULL;
92}
93
94#endif //_MRANDOMSET_H_
95