0
\$\begingroup\$

I don't know if it is any good. I've never done this, thus, I noticed it is kinda slow.

Can you suggest improvements? I may use it in actual software in the future.

private int secgen(int minvalue, int maxvalue)
    {
        Func<int, int, int, int> modular = (a, b, mod) => 
        {
            long rem;
            Math.DivRem((long)a + (long)b, (long)mod, out rem);

            if (rem < minvalue)
                rem += minvalue;

            return (int)rem;
        };


        byte[] entropyBytes = new byte[257];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

        rng.GetBytes(entropyBytes);
        int value = entropyBytes[0];
        for (int i = 1; i < 257; i++) 
        {
            value = modular(value, entropyBytes[i], maxvalue);


        }

        //MessageBox.Show(value.ToString());
        return value;
    }
\$\endgroup\$
  • 2
    \$\begingroup\$ What do you need the random numbers for ? \$\endgroup\$ – Denis Jul 17 '16 at 22:43
  • 3
    \$\begingroup\$ "good" has different meanings when it comes to random number generators. Uniformity, Independence, Replication, Cycle length, Speed, Memory usage, etc. Depends what you're going for. \$\endgroup\$ – craftworkgames Jul 18 '16 at 7:14
  • 1
    \$\begingroup\$ The algorithm does not work correct: For instance: MinValue: 10000 and MaxValue: 10010 produces values like: 18752, 19675, .... \$\endgroup\$ – JanDotNet Jul 18 '16 at 8:48
  • \$\begingroup\$ @JanDotNet Thanks for catching that. I used a lazy method adding MinValue to the remainder \$\endgroup\$ – looseblank Jul 18 '16 at 16:15
1
\$\begingroup\$

You may improve performance:

I would use the modulo operator instead of a function call you aren't benefiting from 100%. Math.DivRem returns a value (quotient) that you don't use. Same result:

var rem = a + b % mod;

Saves you a few unboxing operations and method call

Func<int, int, int, int> modular = (a, b, mod) =>
{
    var rem = a + b % mod;

    if (rem < minvalue)
        rem += minvalue;

    return rem;
};

Saves half the time? http://pastebin.com/XTaLCQh4

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks, I've always had trouble finding the right operators in the language. \$\endgroup\$ – looseblank Jul 18 '16 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.