This is the code I use to generate random bytes array. It is perfectly OK, the only thing is there's a number (or numbers) I don't want. My question is, how can I ensure that, this unwanted number(s) is not included in the results, without having to go through each result?
Random rnd = new Random();
Byte[] bytes = new Byte[50];
rnd.NextBytes(bytes);
For a byte I use this function;
int b = rnd.Next(min, (max + 1))
return (byte) b;
where I can control the result range, but repeated calls to this function will not give a good results.
Your problem can be easily solved with a Monte Carlo algorithm. This is what @SteveLillis is going on about, but it's an incomplete answer. So here is it in full.
void Main()
{
var exclusions = new HashSet<byte> { 1, 200, 58, 11, 66, 9 };
var results = RandomBytes()
.Where(b => exclusions.Contains(b) == false)
.Take(50)
.ToArray();
}
public IEnumerable<byte> RandomBytes()
{
var random = new Random();
byte[] buffer = new byte[32];
while(true)
{
random.NextBytes(buffer);
foreach(var ret in buffer)
{
yield return ret;
}
}
}
RandomBytes() is a stream of random bytes, pretty simple right?
Then we exclude anything from the stream that we don't like, with Where(b => exclusions.Contains(b) == false). The hashset is for "efficiency", but it doesn't help with byte (just put it in due to habit).
Take(50), we only want 50 from the stream.
ToArray give me the results as an array.
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