TeddySnow
TeddySnow

Reputation: 11

Find combination of numbers with backtrack

I'm looking for a backtrack algorithm in C# that will search the correct numbers from a List<int> where the sum of these numbers is closest to X.


e.g: list={5,1,3,5}, X = 10 the output should be (5,5) (5+5 is the closest to 10) it cant be (3,3,3,1) because I can't use a number more than once from the List. (if we have two piece from number 3 than we can use two times)

e.g.2: list={4,1,3,4}, X=10 the output should be {4,1,3} and {1,3,4}.

I got this kind of code to start, but i cant do it; (I know there are wikipedia about backtracking, and knapsack, but it doesn't help me)

static void BackTrack(int lvl, bool Van, int[] E)
{
   int i = -1;
   do
   {
      i++;
      if (ft(lvl, i))
      {
         int k = 0;
         while (k < szint && fk(E[i], E[k]))
         {
            k++;
         }
         if (k == szint)
         {
            E[k] = R[lvl,i];
            if (lvl == E.Length - 1)
            {
            }
            else
            {
               BackTrack(lvl + 1, Van, E);
            }
         }
      }
   } 
   while (i < E.Length - 1);
}

static bool fk(int nr, int nr2)
{
   return (nr + nr2 <= 10);
}

static bool ft(int lvl, int nr)
{
   return true;
}

Upvotes: 1

Views: 1534

Answers (1)

Delta
Delta

Reputation: 851

From what i am reading, this example:

e.g.2: list={4,1,3,4}, X=10 the output should be {4,1,3} and {1,3,4}.

output should be {4,1,4} 9 is closer then 8.

Here is what i did. it works with the two examples you gave.

public List<int> highest(List<int> list, int number)
    {
        //probably a better way to do this
        IEnumerable<int> orderedList = list.OrderByDescending(item => item);

        var currentNumber = 0;
        List<int> combinationResult = new List<int>();
        foreach (var item in orderedList)
        {
            var temp = currentNumber + item;
            if (temp <= number)
            {
                combinationResult.Add(item);
                currentNumber = temp;
            }
        }
        return combinationResult;
    }

Upvotes: 1

Related Questions