C++ 随机抽奖

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35721743/article/details/83758733

随机抽奖实现

各个奖项都有不同的权重,比如一等奖的权重为10,二等奖的权重为30,三等奖的权重为60等。总的权重没必要加起来等于100。代码实现如下:

#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;
}

参考:
http://www.cplusplus.com/reference/cstdlib/rand/

展开阅读全文

没有更多推荐了,返回首页