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;
}
-
2\$\begingroup\$ What do you need the random numbers for ? \$\endgroup\$Denis– Denis2016年07月17日 22:43:12 +00:00Commented Jul 17, 2016 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– craftworkgames2016年07月18日 07:14:40 +00:00Commented Jul 18, 2016 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– JanDotNet2016年07月18日 08:48:21 +00:00Commented Jul 18, 2016 at 8:48
-
\$\begingroup\$ @JanDotNet Thanks for catching that. I used a lazy method adding MinValue to the remainder \$\endgroup\$looseblank– looseblank2016年07月18日 16:15:27 +00:00Commented Jul 18, 2016 at 16:15
1 Answer 1
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
-
\$\begingroup\$ Thanks, I've always had trouble finding the right operators in the language. \$\endgroup\$looseblank– looseblank2016年07月18日 16:14:02 +00:00Commented Jul 18, 2016 at 16:14