Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number with fixed average

I want to generate 100 random numbers between 1 and 10. But the average of those 100 random numbers should be 7. How can I do that? I am doing as follows:

//generating random number
Random random = new Random();
int value = random.Next(1,10);

And storing each value in an array. If the average of 100 items in the array is not 7 then I need to get another 100 random numbers. Can anyone suggest a better way of doing this?

like image 315
M.S Avatar asked Sep 10 '14 09:09

M.S


1 Answers

public int RandomNumberThatAveragesToSeven()
{
    //Chosen by fair dice roll
    //Guaranteed to be random
    return 7;
}

Without additional parameters, this above algorithm satisfies each and every requirement.

  1. Return must be between 1 and 10
  2. Average of multiple calls must tend to 7 as n tends to inf.

EDIT Since there was so much controversy on this answer...I added this answer...which is definitely random.

public List<int> ProduceRandom100NumbersWithAverageOfSeven()
{
    var rand = new Random();
    var seed = rand.Next();
    if(seed > 0.5)
    {
        return new List(Enumerable.Concat(
                 Enumerable.Repeat(6, 50),
                 Enumerable.Repeat(8, 50)));
    }
    else
    {
        return new List(Enumerable.Concat(
                 Enumerable.Repeat(8, 50),
                 Enumerable.Repeat(6, 50)));

    }
}
like image 176
Aron Avatar answered Oct 12 '22 00:10

Aron