随机数的生成

 帮同学写了一个程序:
随机生成一个数组,总共有16个元素,每个元素是0-15,但是每个元素不能重复,但是要求第一个和最后一个必须是0.3.12.15 

#include <time.h>
#include <iostream>
#include <vector>

using namespace std;

int a[16]={0};


void randperm()
{

int i, m;
for(i=0; i<16; ++i)
{
while(a[m=rand()%16]!=0);
a[m] = i;
}
}

int main()
{
int i,m;
vector<pair<int,int>> swp;
srand(unsigned(time(0)));
randperm();
for(i=1;i<15;i++)
{
if(a[i]==0||a[i]==3||a[i]==12||a[i]==15)
{
pair<int,int> pr=make_pair(i,a[i]);
swp.push_back(pr);
}
}
if(a[0]!=0||a[0]!=3||a[0]!=12||a[0]!=15)
{
swp[m=rand()%swp.size()].second = a[0];
a[0]=a[swp[m].first];
a[swp[m].first] = swp[m].second;
swp.erase(swp.begin()+m);
}
if(a[15]!=0||a[15]!=3||a[15]!=12||a[15]!=15)
{
swp[m=rand()%swp.size()].second = a[15];
a[15]=a[swp[m].first];
a[swp[m].first] = swp[m].second;
swp.erase(swp.begin()+m);
}
for(i=0;i<16;i++)
{
cout<<a[i]<<" ";

}
cout << endl;

system("pause");
return 0;
}

posted @ 2017-02-24 16:19  晋安王爷  阅读(153)  评论(0编辑  收藏  举报