jeudi 2 mars 2017

C# Random algorithm until fulfills condition

I have the following scenario:

  1. Generate n numbers of random number from a certain range
  2. Sum all the numbers
  3. Check if the sum == x (x is a number set by user)
  4. if sum != x then keep running the loop
  5. If sum == x, then display the list of random numbers that sum up to x

Based on this logic, I was able to do so but it takes forever to achieve the result, is there any better / way to solve this problem?

    static void Main(string[] args)
    {
        Console.WriteLine("starting...");
        List<int> checkList = generate(5);
        while(!checkSum(checkList, 100))
        {
            checkList = generate(5)
        }
        Console.WriteLine("done!");
    }


    private static bool checkSum(List<int> n, int sum)
    {
        if(n.Sum() == sum)
        {
            return true;
        }
        else
        {
            return false;
        }
    }


    public static List<int> generate(int n)
    {
        Random rng = new Random();
        List<int> list = new List<int>();
        for (int i = 0; i < 5; i++)
        {
            int ran = rng.Next(5, 20);
            list.Add(ran);
        }

        return list;
    }




Aucun commentaire:

Enregistrer un commentaire