Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A more-random number generator.
using System;
using System.Security.Cryptography;
namespace System {
///<Summary>A "More Random" random number generator.</Summary>
class CryptoRandom<T> : Random where T : HashAlgorythm {
// this is simply a "More Random" way to get entropy.
protected override double Sample( )
// Stores the hashed value. Initially, only one.
byte[] entro = { (byte)(base.Sample()*Byte.MaxValue) };
// Since we declare that T must derive from HashAlgorythm, we can safely do this.
HashAlgorythm hashr = new T();
// Return value (later div'd by int.MaxValue, 0x7FFFFFF)
int accumulator=0;
// Compute the hash value of the "original" sampled value.
entro = hashr.ComputeHash(entro);
// Add and shift right one.
// For the binary-math confused: a simple Left-Shift by 1 is /logically/ a *2.
for(int idx=0;idx<entro.Length;idx++){ accumulator += entro[idx]; accumulator << 1; }
// Return a value between 0...1 by dividing the accumulator over the Max value of an Int.
return (float)accumulator/(float)int.MaxValue;
public override int Next()
// Return an int. Oddly enough, undoing the last bit of Sample().
return (int) (Sample() * int.MaxValue);
public override int Next(Int32 MinValue, Int32 MaxValue)
// This makes A logical assumption: MaxValue > MinValue.
return (MinValue)+ ( ( MaxValue - MinValue ) * Sample());
// Returns between 0 and MaxValue. Simple Sample()*MaxValue is a percentage hack.
public override int Next(Int32 MaxValue) { return (Int) ( Sample()*MaxValue); }
// NextDouble simply returns the next sampled value.
public override double NextDouble() { return Sample(); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.