首页 > 解决方案 > C# 从有限组合列表中选择

问题描述

我已经看到很多关于此类主题的已回答问题,但我需要知道在给定值列表(1,5,10,20)和限制数(100)的情况下限制可能组合数量的最佳方法是什么。

我的问题是,我该如何避免类似(100*1 or 20*5)的结果,并且只选择限制为 10 个单位(4*20+4*5)(3*20+7*5)或的结果(9*10+1*5)

不需要的组合:

 (20*5), (100*1), (15*5+25*1), (40*1+12*5), etc

所需组合(等于或小于 100):

 (3*20+7*5), (8*10+1*20), (4*20+1*10+2*5), etc

我想要的是小于或等于 100 的所有可能组合,以及(假设是硬币)不超过 10 个硬币的组合。

这段代码解决了限制结果的问题,但只显示了一个结果:

   class Program
   {
   static int amount = 1000;

   static void Main(string[] args)
   {
        Coin[] c = new Coin[] { new Coin(500, 3), new Coin(200, 3), new Coin(100, 3) ,
                                new Coin(50, 3), new Coin(20, 3), new Coin(10, 3),
                                new Coin(5, 3), new Coin(2, 3), new Coin(1, 3)};
        int netAmount = amount;
        for (int i = 0; i < c.Length; i++)
        {
            amount -= c[i].coveredPrice(amount);
        }
        for (int i = 0; i < c.Length; i++)
        {
            Console.WriteLine(c[i].ToString());
        }
        Console.ReadLine();
    }
}

class Coin
{
    private int price;
    private int counted;    
    private int maxNo;

    public Coin(int coinPrice, int coinMaxNo)
    {
        this.price = coinPrice;
        this.maxNo = coinMaxNo;
        this.counted = 0;
    }

    public int coveredPrice(int Price)
    {
        int Num = Price / price;
        if (maxNo == 0)
            return 0;
        if (maxNo != -1)             
            if (Num > this.maxNo - this.counted)
                Num = maxNo;
        this.counted += Num;
        return Num * price;
    }
        public override string ToString()
    {
        return string.Format("{0} x {1} (max {2}) ", this.price.ToString(), this.counted.ToString(), this.maxNo.ToString());
    }
}

}

我应该修改什么才能显示所有结果?

标签: c#combinations

解决方案


我做了一个简单的例子,我相信它会对你有所帮助。

string pattern = @"\(([^)]*)\)";
string expressions = "(4*20+4*5), (3*20+7*5), (9*10+1*5), (9*10+10*5)";
List<string> validCombinations = new List<string>();

Regex regex = new Regex(pattern);

foreach (Match match in regex.Matches(expressions))
{
      string expression = match.Value;

      using (System.Data.DataTable table = new System.Data.DataTable())
      {
           string result = table.Compute(expression, string.Empty).ToString();

           if (double.TryParse(result, out double res) && res <= 100)
           {
                validCombinations.Add(expression);
           }
      }
 }

 var final = string.Join(",", validCombinations);

如果您在下面有任何问题评论:)


推荐阅读