Randomize a string in C

前端 未结 3 1031
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 10:59

I\'m trying to generate random permutations of an 80-character fixed string in C. Much to my dismay, the system I\'m working on lacks strfry(). What\'s the best way for me to

相关标签:
3条回答
  • 2021-02-06 11:19

    Just use the Open Source GLIBC implementation, as found by Google Code.

    char *
    strfry (char *string)
    {
      static int init;
      static struct random_data rdata;
      size_t len, i;
    
      if (!init)
        {
          static int state[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
          rdata.state = NULL;
          __initstate_r (time ((time_t *) NULL), state, 8, &rdata);
          init = 1;
        }
    
      len = strlen (string);
      for (i = 0; i < len; ++i)
        {
          int32_t j;
          char c;
    
          __random_r (&rdata, &j);
          j %= len;
    
          c = string[i];
          string[i] = string[j];
          string[j] = c;
        }
    
      return string;
    }
    

    You might want to change the GLIBC specific data types to something more generic.

    This code uses the Fisher-Yates shuffle which is actually quite easy to implement by yourself, and very efficient.

    0 讨论(0)
  • 2021-02-06 11:29

    void gcry_randomize (unsigned char *buffer, size_t length, enum gcry_random_level level)

    Fill buffer with length random bytes using a random quality as defined by level.

    http://www.g10code.com/p-libgcrypt.html

    0 讨论(0)
  • 2021-02-06 11:31

    create a 80-line array, put a character and a random number into each line of the array, then sort the array on the random numbers.

    Rebuild string from sorted array.

    0 讨论(0)
提交回复
热议问题