有1到40,40个数,要求随机分组,随机打印
思路:根据堆排序的交换思路,堆排序是堆调整后,将堆头和堆尾交换,然后除去堆尾,堆调整后,将堆头与此时的堆尾交换。依次。。。综合堆排序交换思路,我们可以在40个数中随机获得一个数,与最后一个交换,然后再随机获得一个数与倒数第二个交换,依次。。。
这里会用到随机获取数的函数:srand((unsigned int)time(NULL)); // 产生随机获取数的种子
rand % 40; // 用来在40以内随机获取一个数
下面为程序:
交换函数:
#include
#include
#include
#define SIZE 40
// 交换函数
void swap (int *a,int i,int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
// 打印函数
void printA(int *a, int len)
{
int i;
for (i = 0;i < len;i++)
{
// 4个数一,行每个数占4个字节
if (i % 4 == 0)
printf ("\n");
printf ("%4d",a[i]);
}
putchar ('\n');
}
int main()
{
srand((unsigned int)time(NULL));
int a[SIZE] = {0};
int len = SIZE;
int i;
// 给数组里赋值
for (i = 0;i < len;i++)
{
a[i] = i+1;
}
// 从后往前遍历,i为最后一个数
for (i = len-1;i >= 0;i--)
{
int index= rand() % (i);
swap (a,i,index); // 交换下标与末尾的值
}
printA (a,len);
return 0;
}
这样的用法还可以用于对人随机分组,假设40个人,假设名字是张1~张40,对其随机分组,因为有是字符串,而字符串是常量,不能直接赋值,这里我们用一个二维数组,然后用strcpy直接覆盖。
strcpy的用法:strcpy(str1,str2),用str2去覆盖str1
思路和上面大致相同,随机获取一个后,先打印出来,然后再和最后一个交换,然后舍弃最后一个。依次。。
int main()
{
srand((unsigned int)time(NULL));
char a[][6] = {"张38","张1","张2","张3","张4","张5","张6","张7","张40",
"张15","张14","张13","张12","张11","张10","张9","张8",
"张16","张21","张22","张29","张28","张30","张36","张37",
"张17","张20","张23","张24","张27","张31","张35","张36",
"张18","张19","张39","张25","张26","张32","张33","张34"};
int i;
for(i = LEN -1;i > 0;i--)
{
int index = rand() % (i);
printf ("%-8s ",a[index]);
strcpy (a[index],a[i]);
if (i % 4 ==0)
printf ("\n");
}
printf ("%s",a[0]);
putchar ('\n');
return 0;
}