洗牌(排列)

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 }

 

原文地址:https://www.cnblogs.com/openix/p/2795453.html