Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.
So it works... but it sucks. The problem being it's always going to produce output like this:
"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
How could it be modified to allow for a more even distribution of values across the range?
public static string RandomRangeOfValuesMaker(int maxNumber)
{
var remainingMaxNumber = maxNumber + 1;
const int numberOfValues = 20;
var rand = new Random();
var builder = new StringBuilder();
for (var i = 1; i < numberOfValues + 1; i++)
{
var currentQuestionMark = rand.Next(remainingMaxNumber);
remainingMaxNumber = remainingMaxNumber - currentQuestionMark;
builder.Append(currentQuestionMark + ",");
}
var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);
return rangeOfValues;
}
Aucun commentaire:
Enregistrer un commentaire