洗牌(排列)

gdb中显示数组内容:p (int [10])*a

一:

   1 #include <stdio.h>                                                                                         
      2 #include <stdlib.h>
      3 #include <time.h>
      4
      5 #define NUM 10
      6 const int shuffle_initial[NUM] = {1,2,3,4,5,6,7,8,9,10};
      7 int shuffle_flags[NUM] = {0};
      8 int shuffle_final[NUM] = {0};
      9
     10 int generate(void)
     11 {
     12     int i , k , j , l , temp;
     13     srand((unsigned int )time(NULL));
     14     for(i = NUM ; i ; i--)
     15     {
     16         k = 0;
     17         j = rand()%i + 1;
     18         do
     19         {
     20             if(shuffle_flags[k++] == 0)
     21                 --j;
     22         }while(j);
     23
     24         --k;
     25         shuffle_final[k] = shuffle_initial[k];
     26         shuffle_flags[k] = 1;
     27         printf("%d\t",shuffle_final[k]);
     28     }
     29         printf("\n");
     30     return 0;
     31 }

 

二、

      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <time.h>
      4
      5 #define NUM 10
      6 int shuffle[NUM] = {1,2,3,4,5,6,7,8,9,10};
      7
      8 int generate(void)                                                                                         
      9 {
     10     int i , k , temp;
     11     srand((unsigned) time(NULL));
     12     for(i = NUM ; i != 1 ; )
     13     {

     /*需要说明下,random函数不是ANSIC 标准,所以random函数最好不要用在gcc编译的程序中,

      如果只使用rand()也会产生随机数,问题在于每次产生的随机数一样!!!

      在gcc环境中需要使用srand()种植一个种子,该种子最好每次都不一样,

      种植固定种子的问题,该随机数序列每次都一样。

     */
     14         temp = rand()%i;
     15         i--;
     16         k = shuffle[temp];
     17         shuffle[temp] = shuffle[i];
     18         shuffle[i] = k;
     19
     20         printf("%d\t", k);
     21     }
     22     printf("%d\n",shuffle[0]);
     23
     24     return 0;
     25 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值