-1

Let's say I have a list of predefined numbers, and a list of predefined max limits.

When a user picks a limit, I need to randomly pick a certain amount of numbers from the first list, up until their totals match (As close to, but never over) the user selected total.

What I've tried so far:

void Main()
{
    List<int> num = new List<int>(){ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17, 18, 19, 20 };
    int maxNum = 17;

    List<int> curNum = new List<int>();
    int curTotal = 0;

    foreach(int sel in num.Where(x => x < maxNum)){

    curTotal += sel;

    if(curTotal <= maxNum){
        curNum.Add(sel);
    }


    }
}

There needs to be x amount of numbers picked. In this case, 5 numbers picked, +- 20 numbers to be randomly picked from, and 1 max values.

So the end list should look like this:

1, 2, 3, 4, 7 (17)
1, 2, 3, 5, 6 (17)
1, 2, 3, 4, 6 (16) <- This will be fine if there isn't a solution to the max value.

TheGeekZn
  • 3,696
  • 10
  • 55
  • 91

2 Answers2

0

I think shuffle + "take while sum < limit" may be what you are looking for.

Something like following:

var shuffledList = num.ToList();
shuffledList.Shuffle();

var sum = 0;
var count = 0;
while (shuffledList[count] + sum < max)
{ 
    sum += shuffledList[count++];
}
return shuffledList.Take(count);
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

Building upon @AlexiLevenkov's answer:

class Program { static void Main(string[] args) { int limit = 17; int listSize = 5;

        List<int> a = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
        a.Shuffle();
        List<int> genList = new List<int>();
        int stoppedCount = 0;

        for (int i = 0; i < a.Count(); i++)
        {

            if (i < listSize)
            {
                genList.Add(a[i]);
                stoppedCount = i;
            }
            else
            {
                break;
            }
        }

        while (genList.Sum() > limit)
        {
            genList.Remove(genList.Max());

            stoppedCount++;
            genList.Add(a[stoppedCount]);
        }
    }

}

static class ThisClass
{
    public static void Shuffle<T>(this IList<T> list)
    {
        Random rng = new Random();
        int n = list.Count;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
}
TheGeekZn
  • 3,696
  • 10
  • 55
  • 91