I have the following scenario:
- Generate
n
numbers of random number from a certain range - Sum all the numbers
- Check if the
sum == x
(x is a number set by user) - if
sum != x
then keep running the loop - If
sum == x
, then display the list of random numbers that sum up tox
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