vendredi 19 octobre 2018

How to randomize a number based on criteria in C#?

I am struggling with a randomize algorithm which I'm unable to solve.

Below is the randomize criteria.

  1. User type a random integer number, i.e 28
  2. User type a factor number, i.e 1.2
  3. The total sum of the randomize number must be equals to 28 + 1.2 = 29.2
  4. There should be a total of 28 randomize number generated which the sums of it must equals to 29.2
  5. For each randomize number must be the value between 0.01 to 9.99, maximum two decimals.

I have done my code but I can't seems to get the sums right. Anything i missed out?

namespace RandomizeAlgo
{
    public static class Extend
    {
        public static double RandomNumberBetween(this Random random, double minValue, double maxValue)
        {
            var next = random.NextDouble();

            return minValue + (next * (maxValue - minValue));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var rnd = new Random();
            var totalPeople = 28;
            var factor = 1.2;
            var totalSumNumber = totalPeople + factor;
            var balance = totalSumNumber; 
            var defaultMin = 0.01;
            var defaultMax = 9.99;
            var listOfRandomizedNumber = new List<double>();
            while (true)
            {
                var iteration = 0;
                for (var i = 1; i <= totalPeople; i++)
                {
                    var randomizeResult = 0.00;
                    if (balance >= defaultMax)
                    {
                        randomizeResult = rnd.RandomNumberBetween(defaultMin, defaultMax);
                        randomizeResult = Math.Round(randomizeResult, 2);
                    }
                    else
                    {
                        randomizeResult = rnd.RandomNumberBetween(defaultMin, balance);
                        randomizeResult = Math.Round(randomizeResult, 2);
                    }
                    listOfRandomizedNumber.Add(randomizeResult);
                    balance = balance - randomizeResult;

                    Console.WriteLine(string.Format("{0:0.00}", randomizeResult));
                }

                iteration++;
                //Assertion
                var total = listOfRandomizedNumber.Sum().ToString("0.00");
                if (total != totalSumNumber.ToString("0.00"))
                {
                    throw new InvalidOperationException("Total #"+ iteration + " iteration is: " + total + " . Invalid Randomize Number. Sum does not match");
                }
            }
        }

    }
}




Aucun commentaire:

Enregistrer un commentaire