C # algorithm - find the least number of objects needed

Let's say I have the following code.

var numberToGetTo = 60; 
var list = new[] {10, 20, 30, 40, 50};

I want to be able to return 50 and 10 from a list in = 60.

If the ToGetTo number was 100, I would like to return 50, 50.

If the ToGetTo number was 85, I would like to return 50, 40.

I want to return the smallest number of numbers from the list needed to access "numberToGetTo", while remaining closest (equal to or greater) than to it.

Does something like this possible with Linq?

+3
source share
6 answers

NP- , . , . , .

alt text

+13

, Linq, . .

, , NP-Complete, . O (n ^ 2) .

    static IEnumerable<int> Knapsack(IEnumerable<int> items, int goal)
    {
        var matches = from i in items
                      where i <= goal
                      let ia = new[] {i}
                      select i == goal ? ia : Knapsack(items, goal - i).Concat(ia);

        return matches.OrderBy(x => x.Count()).First();
    }
+6

, , . " ", , - A N , N N, N * A > target.

, , . , - "" , "" "", . , 100, [55,55] [20,20,20,20,20]?

+2
+1

, . , Linq:)

0

, , - . - ?

public class App
{
    static void Main(string[] eventArgs)
    {
        var list = new[] {10, 20, 30, 40, 50};
        var whatYouNeed = GetWhatYouNeed(list, 60, 60);
        //what you need will contain 50 & 10

       //whatYouNeed = GetWhatYouNeed(list, 105,105);
        //what you need will contain (50,50, 10)
    }

    private static IList<int> _whatYouNeed = new List<int>();


    static IEnumerable<int> GetWhatYouNeed(IEnumerable<int> list, int goal, int amountRequired)
    {   //this will make sure 20 is taken over 10, if the goal is 15. highest wins
        var intYouNeed = list.OrderBy(x => Math.Abs(amountRequired - x)).FirstOrDefault(x => x > amountRequired);
        if (intYouNeed == 0) intYouNeed = list.OrderBy(x => Math.Abs(amountRequired - x)).FirstOrDefault();
        _whatYouNeed.Add(intYouNeed);

        if (_whatYouNeed.Sum() < goal)
        {
            int howMuchMoreDoYouNeed = goal - _whatYouNeed.Sum();
            GetWhatYouNeed(list, goal, howMuchMoreDoYouNeed);
        }

        return _whatYouNeed;
    }
}

, GetWhatYouNeed, .

0

Source: https://habr.com/ru/post/1726260/


All Articles