class randomGenerator {
private:
struct val {
unsigned int min;
unsigned int max;
val(unsigned int a, unsigned int b) : min(a), max(b) {
}
};
std::map<int, val> data;
typedef std::map<int, val>::iterator dataIter;
unsigned int increment;
inline int get_random_value(int max_range) {
return (int) (double(max_range)*(rand() / (RAND_MAX + 1.0)));
}
public:
explicit randomGenerator(std::map<int, unsigned int> & params) {
if (params.empty()) {
return;
}
increment = 0;
std::map<int, unsigned int>::iterator it = params.begin();
while (it != params.end()) {
unsigned int first = increment;
unsigned int second = (increment += it->second);
data.insert(std::make_pair(it->first, val(first, second)));
++it;
}
}
int generate() {
unsigned int randVal = get_random_value(increment);
dataIter iter = data.begin();
while (iter != data.end()) {
if (iter->second.min <= randVal && randVal < iter->second.max) {
return iter->first;
}
++iter;
}
return 0;
}
};<pre class="cpp" name="code">#define BALLON_HIGH_ITEM_COUNT 2
#define BALLON_MIDDLE_ITEM_COUNT 18
#define BALLON_LOW_ITEM_COUNT 10
<pre class="cpp" name="code"> int typeArr[3] = {BALLON_HIGH_ITEM_COUNT,BALLON_MIDDLE_ITEM_COUNT,BALLON_LOW_ITEM_COUNT};
std::map<int, uint32_t> probability;
probability.insert(std::make_pair((int)BALLON_HIGH_ITEM_TYPE,BALLON_HIGH_ITEM_COUNT));
probability.insert(std::make_pair((int)BALLON_MIDDLE_ITEM_TYPE,BALLON_MIDDLE_ITEM_COUNT));
probability.insert(std::make_pair((int)BALLON_LOW_ITEM_TYPE,BALLON_LOW_ITEM_COUNT));
randomGenerator *randObject = NULL;
while (true)
{
if (randObject == NULL) {
randObject = new randomGenerator(probability);
}
//randomGenerator randObject(probability);
uint32_t index = randObject->generate();
--typeArr[index-1];
if (typeArr[index-1] == 0) {
probability.erase(index);
delete randObject;
randObject = NULL;
}
uint32_t rand = get_random_value(allItemConfigByType[index].size());
pInfo->ballon[at] = allItemConfigByType[index][rand];
if (BALLON_HIGH_ITEM_TYPE == index) {
DEBUG_LOG("randomGenerator random_index:%d|rand:%d|", index, rand );
DEBUG_LOG("randomGenerator allItemConfigByType:%d|", allItemConfigByType[index].size() );
SBallonRandomItemInfo pTemp = allItemConfig[pInfo->ballon[at]];
if (reward_at == 1 && pInfo->show_reward[0].good_id == pTemp.itemid) {
pInfo->ballon[at] = allItemConfigByType[index][(rand+1)%allItemConfigByType[index].size()];
pTemp = allItemConfig[pInfo->ballon[at]];
}
pInfo->show_reward[reward_at].good_id = pTemp.itemid;
pInfo->show_reward[reward_at].count= pTemp.count;
reward_at++;
}
if (++at >=BALLON_COUNT_MAX) {
break;
}
}
if (randObject) {
delete randObject;
}