编号为1-1000的1000个数,随机配成500对,怎么实现?
编号为1-1000的1000个数,随机配成500对,不能有(i,i),而且(i,j)和(j,i)算相同的一对,具体怎么实现?
[解决办法]
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define NUM 1000
int main()
{
int i,j,p,a[NUM];
time_t t;
srand((unsigned) time(&t));
for(i=0;i <NUM;i++){
a[i]=rand()%NUM;
for(j=0;j <i;j++)
if(a[j]==a[i]){
i--;
break;
}
}
for(p=0;p <NUM;p=p+2)
printf( "(%4d,%4d)\t ",a[p],a[p+1]);
}
[解决办法]
我来写一下吧
c++的
#include <iostream.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int visit[1000]={0};
struct match
{
int x;
int y;
};
void main()
{
match a[500];
srand((unsigned) time(NULL));
for(int pass=0;pass <500;pass++)
{
a[pass].x=rand()%1000+1;
a[pass].y=rand()%1000+1;
if(visit[a[pass].x-1]==0&&visit[a[pass].y-1]==0&&a[pass].x <a[pass].y)
{
visit[a[pass].x-1]=1;
visit[a[pass].y-1]=1;
}
else pass--;
}
for(int i=0;i <500;i++)
{
cout < <a[i].x < < " " < <a[i].y < <endl;
getchar();
}
}