基于游戏抽卡期望的C++代码测试

游戏玩法

已知你有一个n*n的全暗面板,当你抽奖时随机一个面板将被点亮,求抽奖多少次才能将其全部点亮的期望

游戏代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<string.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#include<map>
#include<sstream>
#include<time.h>
#include<set>
#include<unordered_set>
#include<unordered_map>
#include<limits.h>
#include<numeric>
#include<math.h>
using namespace std;
#define EPS 1e-4
#define GROUP_T 10
#define T 100000
#define N 100
#define M 101
#define MAX 0x3f3f3f3f
#define MIN -MAX
#define MOD 1000000007
#define P 499
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<pll, ll> plll;


bool grid[N][N];


int test(int num,int n) {
    memset(grid, false, sizeof(grid));
    int light = 0;
    int target = n * n;
    int cnt = 0;
    while (light < target) {
        ++cnt;
        int x = rand() % n;
        int y = rand() % n;
        if (!grid[x][y]) {
            grid[x][y] = true;
            ++light;
        }
    }
    //printf("第%d次抽奖,一共花费%d次\n", num,cnt);
    return cnt;
}


int main() {
    srand((unsigned int)time(NULL));

    for (int k = 1;k <= GROUP_T;++k) {
        int sum = 0;
        int mincnt = MAX;
        int maxcnt = MIN;

        int begin = clock();
        for (int i = 1;i <= T;++i) {
            int cnt = test(i, k);
            sum += cnt;
            mincnt = min(mincnt, cnt);
            maxcnt = max(maxcnt, cnt);
        }
        int end = clock();
        printf("%dx%d: ", k, k);
        printf("最少抽%d次,最多抽%d次\n平均抽%.2lf次 一共花费%ds\n", mincnt, maxcnt, (double)sum / T, (end - begin) / 1000);
    }
}

代码解释

本代码测试了n为1-10的面板期望,其中对于每个n采取测试100000次求平均值的方法求期望,顺便求了每个n下的抽奖最少和最多测试,希望对大家抽卡有所帮助和了解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值