【发布时间】:2016-03-12 09:42:51
【问题描述】:
这很难,至少对于我的最低 c 技能而言。
基本上,用户将价格列表输入到数组中,然后输入他想要购买的商品数量,最后是不超过的最大成本。
我需要检查所需数量的项目有多少组合小于或等于给定的成本。
如果问题是组合中的项目数量固定,比如 3 个,那么只需三个循环选择每个价格并将它们添加到测试中就会容易得多。
我被难住的地方是要求用户输入任意数量的项目,最多为数组中的项目数。
这是我最初决定的,后来我意识到用户可以指定任意数字的组合,而不仅仅是三个。它是在此处类似主题的帮助下创建的,但同样,它仅在用户指定他想要每个组合 3 个项目时才有效。否则它不起作用。
// test if any combinations of items can be made
for (one = 0; one < (count-2); one++) // count -2 to account for the two other variables
{
for (two = one + 1; two < (count-1); two++) // count -1 to account for the last variable
{
for (three = two + 1; three < count; three++)
{
total = itemCosts[one] + itemCosts[two] + itemCosts[three];
if (total <= funds)
{
// DEBUG printf("\nMatch found! %d + %d + %d, total: %d.", itemCosts[one], itemCosts[two], itemCosts[three], total);
combos++;
}
}
}
}
据我所知,没有简单的方法可以根据用户希望的每个组合的项目数量来灵活调整它。
如果能提供任何帮助,我将不胜感激。
【问题讨论】: