Search code examples
c#functionaverageinverse

How can I do an average reverse in c#?


I need to create a function that if i enter a number, return 3 numbers that your averange is the same number that I pass

for example

if i entered the number 3,92 the return value is a list of numbers 3,89 3,57 4,3 (Randomize)


Solution

  • Here is a method that will do just that.

    public double[] AverageReverse(double targetAverage, double range)
    {
        var r = new Random(); // TODO: Cache it between calls to avoid "why does ny Random class only produce the same numbers?"
        var n1 = targetAverage - r.NextDouble() * range;
        var n2 = targetAverage + r.NextDouble() * range;
        var n3 = 3 * targetAverage - (n1 + n2);
    
        return new[] { n1, n2, n3 };
    }
    

    Example:

    var ar = AverageReverse(3.92, 0.5);
    // returns (example):
    //   3,76575929136284 
    //   3,98495292557634 
    //   4,00928778306082 
    // average:
    //   3.92
    

    The way it works is that by solving the following equation:

    average = (n1 + n2 + n3) / 3
    

    for n3 gives:

        average             = (n1 + n2 + n3) / 3
    3 * average             =  n1 + n2 + n3
    3 * average - (n1 + n2) =            n3
    

    thus:

    n3 = 3 * average - (n1 + n2)