69,371
社区成员
发帖
与我相关
我的任务
分享
#include <cstdlib>
#include <vector>
#include <iostream>
#include <iomanip>
#define N 5
using namespace std;
int count[N]={0,0,0,0,};
void random1()
{
for( int i=0; i<N; ++i)
{
count[i]=1;
}
for( int i=0; i<100-N; ++i)
{
count[rand()%5]++;
}
}
int zero_index()
{
for( int i=0; i<N; ++i)
{
if( count[i] == 0)
return i;
}
return -1;
}
void random2()
{
for( int i=0; i<100; ++i)
{
count[rand()%5]++;
}
int index=0;
while( index=zero_index(), index!=-1) //如果有0的情况
{
vector<int> more_than2;
for( int i=0; i<N; i++)
if( count[i]>=2) more_than2.push_back(i);
count[index]++;
count[more_than2[rand()%more_than2.size()]]--; //多余2个的中的一个数的个数减去1,也是随机的
}
}
int main()
{
srand((unsigned int )time(0)); //加随机种子
// rondom1();
random2();
for( int i=0; i<N; i++)
cout <<"Number " << i+1 << " : " << setw(3) <<count[i] << endl;
return 0;
}