[模板] 随机数 Random
Templates 其他 Random
Lastmod: 2021-05-17 周一 21:05:34

随机数 Random

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;

struct FastIO { 
    FastIO() { ios::sync_with_stdio(false); cin.tie(nullptr); }
}fastio;

mt19937 rnd(chrono::system_clock::now().time_since_epoch().count());
mt19937_64 rnd_64(chrono::system_clock::now().time_since_epoch().count());

// [0,r)
int rndi(int r) { return rnd()%r; }
// [l,r] r-l+1<=INT_MAX
int rndi(int l,int r) { return rnd()%(r-l+1)+l; }
LL rndll(LL l,LL r) { return rnd_64()%(r-l+1)+l; }
char rndc() { return rndi(-128,127); }
char rndc(const string &s) { return s[rndi(s.length())]; }
char rnd_lower() { return rndi(26)+'a'; }
char rnd_upper() { return rndi(26)+'A'; }
char rnd_digit() { return rndi(10)+'0'; }
char rnd_alpha() { int r=rndi(52); return r<26?(r+'a'):(r-26+'A'); }
char rnd_alphadigit()
{
    int r=rndi(62);
    if(r<10) return r+'0';
    if(r<36) return r-10+'a';
    return r-36+'A';
}

template<typename T>
vector<T> rnd_vec(int n,const function<T(void)> &f)
{
    vector<T> vec;
    while(n--) vec.push_back(f());
    return vec;
}
vector<int> rnd_vii(int n,int l,int r)
{ return rnd_vec<int>(n,[=](){ return rndi(l,r); }); }
vector<LL> rnd_vll(int n,LL l,LL r)
{ return rnd_vec<LL>(n,[=](){ return rndll(l,r); }); }
string rnds(int n,const function<char(void)> &f)
{
    string s;
    while(n--) s+=f();
    return s;
}

int main()
{
    cout<<rnds(10,rnd_lower)<<endl;
    cout<<rnds(10,rnd_upper)<<endl;
    cout<<rnds(10,rnd_digit)<<endl;
    cout<<rnds(10,rnd_alpha)<<endl;
    cout<<rnds(10,rnd_alphadigit)<<endl;
    cout<<rnds(10,[](){ return rndc("abc"); })<<endl;

    auto vecii=rnd_vii(10,-100,100);
    for(int i:vecii) cout<<i<<" ";
    cout<<endl;

    auto vecll=rnd_vll(5,-1000000000000L,1000000000000L);
    for(LL i:vecll) cout<<i<<" ";
    cout<<endl;
    return 0;
}
Prev: [模板][数据结构] 离散化 Discretization
Next: 《C++ Primer》 拾遗 第 2 章 变量和基本类型