c# - 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());
}
}
}
我应该修改什么才能显示所有结果?
解决方案
我做了一个简单的例子,我相信它会对你有所帮助。
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);
如果您在下面有任何问题评论:)
推荐阅读
- c++ - 如何解决“数组初始值设定项必须是初始值设定项列表”错误?
- python - Jupyter notebook 设置项目依赖
- ios - 苹果开发者控制台中的产品未在应用程序内显示
- sql-server - 在 sql server 中将 varchar yyyy-mm-dd T hh:mm 转换为 datetime2
- h2 - Spring R2DBC - 使用 schema.sql 和 ConnectionFactoryInitializer 创建 h2 表时出现“表已存在”错误
- c# - 使用datagridview列C# SQL搜索数据库
- javascript - 自 API 更新以来如何修复 SoundCloud 播放器?
- javascript - MongoDB - MongooseJS - 从父级检索 ID 以在集合中设置子级
- c# - Microsoft.office.interop.msproject 在我的本地电脑上工作正常,在将我的应用程序部署到天蓝色后无法工作
- android - 从 react native 定期发送位置到后端 api