C++随机数

一、C++ 随机数的两套体系

C++ 随机数方案:
├── 旧方案(C风格):rand() / srand()     ← 简单但缺陷多
└── 新方案(C++11):<random> 库          ← 推荐,功能强大

二、旧方案:rand() / srand()

基本用法

#include <iostream>
#include <cstdlib>   // rand(), srand()
#include <ctime>     // time()
using namespace std;

int main() {
    srand(time(0));  // 用当前时间作种子(每次运行结果不同)
    /*

    Unix 时间戳(Unix Timestamp),表示:

    从 1970年1月1日 00:00:00 UTC 到现在,经过了多少秒

    为什么从 1970 年开始?
    这个起点叫做 Unix 纪元(Unix Epoch),是 Unix 操作系统诞生时定的约定——1970年1月1日午夜                                             UTC 作为时间零点,全世界的 Unix/Linux/Windows 系统都沿用至今。

   
	为什么用time(0)做随机种子:
	每秒钟 time(0) 的值都不同
	→ 每次运行程序时种子不同
	→ rand() 产生的序列不同
	→ 实现"每次结果不一样"的效果 
	
	缺点:
    同一秒内运行两次,种子相同,随机序列完全一样!
    srand(time(0));  // 精度只到秒级

    // ✅ 更好的方案(精度到纳秒)
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
    */
    
    for (int i = 0; i < 5; i++) {
        cout << rand() << endl;  // 输出 0 ~ RAND_MAX 的随机整数
    }
    return 0;
}

控制随机范围的公式

srand(time(0));

// 公式:rand() % (max - min + 1) + min
int a = rand() % 10;          // [0, 9]
int b = rand() % 10 + 1;      // [1, 10]
int c = rand() % 101;         // [0, 100]
int d = rand() % 50 + 25;     // [25, 74]

// 随机浮点数 [0.0, 1.0)
double f = (double)rand() / RAND_MAX;

// 随机浮点数 [min, max]
double g = (double)rand() / RAND_MAX * (max - min) + min;

旧方案的缺陷

❌ 随机质量差:分布不均匀,低位bit规律性强
❌ RAND_MAX 平台差异:Windows 是 32767,Linux 是 2147483647
❌ 非线程安全:多线程环境下有问题
❌ 不可重复测试:调试时难以复现随机序列

三、新方案:C++11 <random> 库

核心架构

<random> 库 = 随机数引擎 + 分布器
      ↓               ↓
  产生原始随机数    转换为目标分布

常用随机数引擎

#include <random>

mt19937 rng(42);              // 梅森旋转算法,最常用,质量高
mt19937_64 rng64(42);         // 64位版本
default_random_engine rng2;   // 编译器默认引擎

常用分布器

// 均匀整数分布 [a, b]
uniform_int_distribution<int> uid(1, 100);

// 均匀实数分布 [a, b)
uniform_real_distribution<double> urd(0.0, 1.0);

// 正态分布(均值, 标准差)
normal_distribution<double> nd(0.0, 1.0);

// 伯努利分布(概率 p 返回 true)
bernoulli_distribution bd(0.3);  // 30% 概率为 true

// 泊松分布
poisson_distribution<int> pd(4.0);

四、实例演练

实例 1:骰子模拟器

#include <iostream>
#include <random>
using namespace std;

int main() {
    // 用随机设备作种子(真随机)
    random_device rd;
    mt19937 rng(rd());
    
    uniform_int_distribution<int> dice(1, 6);  // 1~6
    
    cout << "=== 投骰子 10 次 ===" << endl;
    for (int i = 0; i < 10; i++) {
        cout << "第 " << i+1 << " 次:" << dice(rng) << " 点" << endl;
    }
    return 0;
}

实例 2:随机密码生成器

#include <iostream>
#include <random>
#include <string>
using namespace std;

string generatePassword(int length) {
    const string chars = 
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%";
    
    random_device rd;
    mt19937 rng(rd());
    uniform_int_distribution<int> dist(0, chars.size() - 1);
    
    string password;
    for (int i = 0; i < length; i++) {
        password += chars[dist(rng)];
    }
    return password;
}

int main() {
    cout << "8位密码:" << generatePassword(8) << endl;
    cout << "16位密码:" << generatePassword(16) << endl;
    cout << "32位密码:" << generatePassword(32) << endl;
    return 0;
}

实例 3:洗牌算法(竞赛常用)

#include <iostream>
#include <vector>
#include <algorithm>  // shuffle
#include <random>
using namespace std;

int main() {
    vector<int> cards = {1,2,3,4,5,6,7,8,9,10,11,12,13};
    
    mt19937 rng(42);  // 固定种子,可复现
    
    // 方法一:std::shuffle(推荐)
    shuffle(cards.begin(), cards.end(), rng);
    
    cout << "洗牌结果:";
    for (int c : cards) cout << c << " ";
    cout << endl;
    
    // 方法二:手动 Fisher-Yates 洗牌
    for (int i = cards.size() - 1; i > 0; i--) {
        uniform_int_distribution<int> dist(0, i);
        int j = dist(rng);
        swap(cards[i], cards[j]);
    }
    
    return 0;
}

实例 4:蒙特卡洛法估算 π

#include <iostream>
#include <random>
#include <cmath>
using namespace std;

int main() {
    mt19937 rng(time(0));
    uniform_real_distribution<double> dist(-1.0, 1.0);
    
    int total = 1000000;  // 总投点数
    int inside = 0;       // 落在圆内的点数
    
    for (int i = 0; i < total; i++) {
        double x = dist(rng);
        double y = dist(rng);
        // 判断点是否在单位圆内
        if (x*x + y*y <= 1.0) {
            inside++;
        }
    }
    
    double pi = 4.0 * inside / total;
    cout << "估算的 π ≈ " << pi << endl;
    cout << "真实的 π = " << acos(-1.0) << endl;
    
    return 0;
}

实例 5:正态分布模拟考试成绩

#include <iostream>
#include <random>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    mt19937 rng(42);
    // 均值75分,标准差10分的正态分布
    normal_distribution<double> nd(75.0, 10.0);
    
    vector<int> scores;
    for (int i = 0; i < 50; i++) {
        int score = (int)nd(rng);
        score = max(0, min(100, score));  // 限制在 [0, 100]
        scores.push_back(score);
    }
    
    sort(scores.begin(), scores.end());
    
    // 简单统计
    double sum = 0;
    for (int s : scores) sum += s;
    
    cout << "最低分:" << scores.front() << endl;
    cout << "最高分:" << scores.back() << endl;
    cout << "平均分:" << sum / scores.size() << endl;
    
    return 0;
}

实例 6:竞赛中的随机化技巧(对抗 hack)

#include <iostream>
#include <random>
#include <chrono>
using namespace std;

// 用时间戳作种子,防止被 hack
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

// 随机打乱输入数据(对抗针对性数据)
void randomShuffle(vector<int>& v) {
    shuffle(v.begin(), v.end(), rng);
}

// 随机选择主元(随机化快排)
int randomPartition(vector<int>& v, int l, int r) {
    uniform_int_distribution<int> dist(l, r);
    int pivot = dist(rng);
    swap(v[pivot], v[r]);
    // ... 正常 partition 逻辑
    return r;
}

五、固定种子 vs 随机种子

// 固定种子:每次运行结果相同 → 调试、竞赛对拍使用
mt19937 rng(42);

// 随机种子(时间):每次运行结果不同 → 一般应用
mt19937 rng(time(0));

// 随机设备种子(真随机):密码学级别 → 安全应用
random_device rd;
mt19937 rng(rd());

// 高精度时间戳:竞赛防 hack 首选
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

六、竞赛场景速查表

场景推荐写法
生成 [l, r] 随机整数uniform_int_distribution<int>(l, r)(rng)
随机打乱数组shuffle(v.begin(), v.end(), rng)
对拍生成数据固定种子 mt19937 rng(42)
防 hack 随机化时间戳种子 + shuffle 输入
随机浮点数uniform_real_distribution<double>(0,1)(rng)

七、两套方案怎么选?

用旧方案 rand():
  ✅ GESP 低级别(1-3级)代码简洁
  ✅ 对随机质量要求不高的小练习

用新方案 <random>:
  ✅ CSP / NOIP / NOI 竞赛(专业、质量高)
  ✅ 需要特定分布(正态、泊松等)
  ✅ 多线程程序
  ✅ 工程项目(游戏、模拟、安全)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值