# C++ 随机抽奖

## 随机抽奖实现

#include<iostream>
#include<map>
#include<ctime>
#include<cstdlib>
using namespace std;

namespace rand_number
{
//在min~max之间随机产生一个数
int randomBetween(int min, int max)
{
if (min == max)
return min;
int rand_value = 0;
if (min > max)
rand_value =max+ (int)((min - max +1.0)*(rand()*1.0/ RAND_MAX));
else
rand_value = min + (int)((max - min + 1.0)*(rand()*1.0/ RAND_MAX));
return rand_value;
}
//RAND_MAX在stdlib.h中被定义成一个常亮 0-32767
//权重之和
int sum_of_weight(map<int, int>&map1)
{
int sum_weight = 0;
for (auto& it : map1)
{
sum_weight += it.second;
}
return sum_weight;
}
//返回几等奖
int random(map<int, int>&map1)
{
int sum_weight = sum_of_weight(map1);
int rand_num = randomBetween(1, sum_weight);
int current = 0;
for (map<int, int>::iterator it = map1.begin(); it != map1.end(); ++it)
{
if (current <= rand_num && rand_num <= current + it->second)
return it->first;
current += it->second;
}
return 0;
}
}

int main()
{
map<int, int> map1;  //key->几等奖  value->weight
map1[1] = 10;
map1[2] = 30;
map1[3] = 60;
srand((unsigned long)time(NULL));
for (int i = 0; i < 10; ++i)
{
int level = rand_number::random(map1);
cout << level << "  ";
}
cout << endl;
system("pause");
return 0;
}