求问各位大佬如何将结构体中的n组数据随机分组,一组5个
说到随机,自然是srand() + rand()的组合来产生随机数。
根据你数组总的数量,设定随机数范围,随机产生选择的下标值,将该下标对应的数据从数组中移除到新的分组中,然后数组范围减去1,直到最后一个就不用随机数了
typedef struct
{
int a;
int b;
}TEST;
TEST test[1000];
int n = 0;
TEST sub[200][5];
int a = 0;
int b = 0;
void add()
{
...//假设此处已经增加了一定量的test数组内容
}
void del(int pos)
{
for(int i=pos;i<n;i++)
{
test[i] = test[i+1];
}
n--;
}
void main()
{
srand((unsigned)time(NULL));
while(n>0)
{
int pos = rand()%n;
sub[a][b++] = test[pos];
if(b==5)
{
a++;
b=0;
}
del(pos);
}
}