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.
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 .
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.
char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26]; which would work with any encoding (including EBCDIC, ASCII, UTF-8, ISO-Latin-1) ....
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With