Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomize a string in C

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 generate a random permutation of this string? Since this will be looped over approx. 100,000 times, performance is an issue.

like image 243
Max Avatar asked Dec 31 '08 10:12

Max


People also ask

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

Can we generate random string?

A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters. All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer. The ints() method from java. util.

How do you generate a random character in C?

char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26]; which would work with any encoding (including EBCDIC, ASCII, UTF-8, ISO-Latin-1) ....

How do you randomize a string in C++?

To generate random characters, we should use the rand() method. It generates integer values at random. This number is created using an algorithm associated with the specific time it is called and returns a succession of seemingly unrelated numbers.


1 Answers

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.

like image 161
Konrad Rudolph Avatar answered Sep 17 '22 22:09

Konrad Rudolph