Generators

1、 生成器 Generator

【注意事项】testlib.h 必须在其他头文件之前加载!!!

1.1、igen.cpp

#include "testlib.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
	registerGen(argc, argv, 1);
	cout << rnd.next(1, 1000000) << endl;
	return 0;
}
  • 要使用生成器必须在程序开始先注册生成器 registerGen(argc, argv[], 1),其中参数 argcargv 就是 main() 传进来的参数,最后面的可选项默认为 1.

官方对此的解释是,如果是较老版本的使用参数 0,2013 年之后的版本默认参数选择 1 就可以

  • 本程序的目的是随机产生一个 \([1, 1000000]\) 区间的整数,可以在命令行传入参数来改变输出结果,生成器的好处就是可以保证在不同机器、不同编译器以及不同操作系统中,只要给定参数一样,所得到的结果也是一样的,以下是几个测试结果

./igen.exe 1 > 959139
./igen.exe 2 > 9859
./igen.exe 2 > 125987

  • NOIP 2005 普及组第一题【陶陶摘苹果】生成数据程序
#include "testlib.h"
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
	registerGen(argc, argv, 1);
	freopen("test.out", "w", stdout); // 重定向标准输出
	for (int i = 1;  i <= 10; i++) {
		cout << rnd.next(100, 200) << " "; // 产生 10 个 100 到 200 之间的随机整数
	}
	cout << endl << rnd.next(100, 120); // 产生一个 100 到 120 之间的随机整数
	return 0;
}

1.2、iwgen.cpp

#include "testlib.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
    registerGen(argc, argv, 1);
    cout << rnd.wnext(1, 1000000, opt<int>(1)) << endl;
    return 0;
}
  • 带权重的随机数生成,最后的参数为 0 的话就等价于 rnd.next(1, 1000000)
  • 当最后的参数是大于 0 的整数时,等价于执行程序
result = rnd.next(1, 1000000);
for (int i = 1; i <= n; i++) // 这里的 n 就是最后的那个参数
	result = max(result, rnd.next(1, 1000000));

也就意味着得到的随机数是偏大的,实现了权重的效果

  • 同理,当最后的参数是小于 0 的整数时,等价于执行程序
result = rnd.next(1, 1000000);
for (int i = 1; i <= -n; i++) // 这里的 n 就是最后的那个参数
	result = min(result, rnd.next(1, 1000000));

这样得到的随机数是偏小的
正权重得到的是区间靠右的随机数,负权重得到的是区间靠左的随机数

for (int i = 1; i <= 10; i++)
	cout << rnd.wnext(1, 1000, 10) << " ";

得到的结果为 644 888 827 985 955 898 867 973 1000 835,整体都是偏大的

for (int i = 1; i <= 10; i++)
	cout << rnd.wnext(1, 1000, -10) << " ";

得到的结果为 42 23 119 2 51 17 237 125 98 56,整体偏小

posted @ 2022-06-13 18:55  哇哩机器人  阅读(206)  评论(0)    收藏  举报