jeudi 8 juin 2017

Random string generator in C#: Unicode out of range?

I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?




Aucun commentaire:

Enregistrer un commentaire