Java算法解决供应商机器“改变给予”问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java算法解决供应商机器“改变给予”问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2724字,纯文字阅读大概需要4分钟。
内容图文
作为一名毕业生,我参加了一个java开发角色的面试,并且在技术考试中做得很好,直到我遇到了这个问题.
如果我正在建立一个自动售货机(为简单起见)返回2英镑的更改.我将如何产生一个列出所有可能的£2组合的实现.
例如£1£1,£1 50p 50p,50p 50p 50p 50p等等..
我怎么能列出自动售货机可能的2.00英镑变化的所有不同组合.
我开始写点什么,这就是我到目前为止所提出的.
它几乎可以工作,但有人可以帮助我找出为什么它没有完全扩展.第二双眼睛会很感激.以及任何可以优化的方式.
多谢你们.
private static void printCoins(int[] tempArray) {
for (int i = 0; i < tempArray.length - 1; i++){
// to stop my array from printing out any non-denominator coins e.g
if (tempArray[i] > 0){
System.out.print(tempArray[i] + ": ");
}
System.out.println("\n");
}
}
public static void vendingMachine() {
int[] denominations = {200,100, 50, 20, 10, 5, 2, 1};
int[] tempArray = new int[50]; //combination of coins made
int total = 200;
int coinCombiIndex = 0, denomCoinIndex = 0;
// whilst all denominations havent been visited
while (denomCoinIndex < denominations.length)
// if i have the correct change
if (total - denominations[denomCoinIndex] == 0){
tempArray[coinCombiIndex] = denominations[denomCoinIndex];
denomCoinIndex++; //increment so that next iteration starts with lower denom
printCoins(tempArray); // return coins
}
// checks to see whether new total minus coin (denominator) is still >= 0
else if (total - denominations[denomCoinIndex] >= 0) {
// if so SUBTRACT from total and ADD coin to coin-combination-array
total = total - denominations[denomCoinIndex];
tempArray[coinCombiIndex] = denominations[denomCoinIndex];
coinCombiIndex++;
}
else {
denomCoinIndex++;
}
// printCoins(tempArray);
}
我的输出
200:
100: 100:
100: 50: 50:
100: 50: 20: 20: 10:
100: 50: 20: 20: 5: 5:
100: 50: 20: 20: 5: 2: 2: 1:
解决方法:
回答你的第二个问题:
只试用{20,10}你会发现你的程序真的不对.
你试图将我的复原转换成循环,我想这是最好的解决方案.但是在一个循环中很难做到这一点(你错过了很多可能性).
您可以尝试在每个步骤中使用不同的约束重新启动while循环,例如在此循环周围添加一个新的while循环
while (i<denominations.length){
total=200;
denomCoinIndex=i;
tempArray = new int[1000];
i++;
但它仍然不够……所以你需要再次添加一些循环,直到你处理所有的情况.
我不认为你的while循环方法在这里是好的.
最简单的方法是使用这样的循环来处理所有可能的解决方案(从类似的问题到你的问题):
int total = 200;
System.out. printf("quarter\tdime\tnickle\tpenny\tto make %d\n", total);
int combos = 0;
for (int q = 0; q <= total / 25; q++)
{
int total_less_q = total - q * 25;
for (int d = 0; d <= total_less_q / 10; d++)
{
int total_less_q_d = total_less_q - d * 10;
for (int n = 0; n <= total_less_q_d / 5; n++)
{
int p = total_less_q_d - n * 5;
System.out.printf("%d\t%d\t%d\t%d\n", q, d, n, p);
combos++;
}
}
}
System.out.printf("%d combinations\n", combos);
希望能帮助到你
内容总结
以上是互联网集市为您收集整理的Java算法解决供应商机器“改变给予”问题全部内容,希望文章能够帮你解决Java算法解决供应商机器“改变给予”问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。