【技巧】生成算法题测试随机数据(文件读取freopen)

随机数rand()知识

【技巧】C/C++生成随机数数组(rand(),srand(),time()函数介绍)
关于rand(),srand()生成随机数原理,本人了解不深,目前仅仅是会简单使用的水平。

生成不同范围随机数方法

基于基本的生成随机数方法,通过一些策略调整所需随机数的范围

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

void Random(int *a,int n,int l,int r)//最大范围:0~32767 
{
	srand(time(0)); 
	for(int i=0; i<n; i++) {
		a[i]=rand()%(r-l+1)+l;//生成区间r~l的随机数
	}
}

// 0000 0000 0000 0000 0111 1111 1111 1111 随机数最大值
// 0111 1111 1111 1111 0000 0000 0000 0000 左移16位
// 从右往左数,第16位永远是0
int Random2(int *a,int n,int max_range) 
{
	srand(time(0)); 
	for(int i=0; i<n; i++) {
		//a[i]= (rand() << 16 | rand()) % max_range; //最大范围:0~2^31-1,实际上不够随机,有一部分数据无法取到
		a[i]= (rand() << 15 | rand()) % max_range; //最大范围:0~2^30-1
	}
}

void Random3(int *a,int n)//最大范围:-32767~32767 
{
	srand(time(0)); 
	for(int i=0; i<n; i++) {
		a[i]=rand();//生成0~32767的随机数
		if(rand()%2) a[i] = -a[i]; //注意,这里的rand()和上一行的不一样! 
	}
}

int main()
{
	int n=10;//数组元素的个数,即生成随机数的个数
	int a[n];
	Random2(a,n,1E9);
	for(int i=0; i<n; i++)
		cout<<a[i]<<" ";
	//cout<<*min_element(a,a+n)<<endl; //输出数组a最大值 
	return 0;
}

生成n个随机数

根据不同算法题实际需要更改

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

int Random(int n)//最大范围:-32767~32767,实际范围 -(n-1)~(n-1),根据需求挑战范围 
{
	int tmp; 
	tmp = rand() % n;
	if(rand()%2) tmp = -tmp; //注意,这里的rand()和上一行的不一样! 
	return tmp;
}

int main()
{
#ifndef ONLINE_JUDGE //本地运行的时候执行该块语句 
    //freopen("in.txt",  "r",  stdin); //读入文件"in.txt"中的数据,本题用不到 
    freopen("out.txt", "w", stdout); //输出数据到同目录文件"out.txt"中 
#endif
	int N=200; //数组元素的个数,即生成随机数的个数
	cout<<N<<endl; //n输出到文件中 
	while(N--)
		cout<<Random(101)<<" ";  //生成200个-100~100的随机数 
	return 0;
}


在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值