C#从有限组合列表中进行选择

时间:2018-08-16 09:38:50

标签: c# combinations

我已经看到许多有关此类主题的已回答问题,但是我需要知道在给定值列表(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());
    }
}

}

我需要修改什么才能显示所有结果?

1 个答案:

答案 0 :(得分:0)

我做了一个简短的例子,相信会对您有所帮助。

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);

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