我被要求解决这个简单的问题,我的编程能力相当惨。在这里,
给定以下元素,找到所有服装元素的组合,使总成本恰好为 100 美元。
这是我的代码:
tshirt=20; %price of tshirt
shorts=15; %price of shorts
socks=5; %price of socks
solution=0;
for i=20 %cannot have more than 20 socks (over $100)
for j = 6 %cannot have more than 6 shorts (over $100)%cannot have more than 20 socks (over $100)
for k=5 %cannot have more 5 tshirts (over $100)
%Some code or function that will add them up so they are
%exactly $100??
tshirt+shorts+socks==100
end
end
end
我知道这段代码很原始,但我不知道如何处理...... 任何帮助将不胜感激。
最佳答案
看来您在这个问题上有一个良好的开端,而且我可以看到您在代码方面遇到了一些困难。我会尽力帮助你。
tshirt=20; %price of tshirt
shorts=15; %price of shorts
socks=5; %price of socks
solution=0;
好的开始,我们知道东西的价格。看来问题出在 for 循环中,您想要遍历所有可能性......
for i = 0:20
for j = 0:6
for k = 0:5
%Check to see if this combonation is equal to 100 bucks
if(i*socks + j*shorts + k*tshirt == 100)
%I'll let you figure out the rest ;)
end
end
end
end
希望这可以帮助您入门。 for 循环实际上所做的是将该变量设置为您提供的数字之间的所有内容(包括在内),并递增 1。这样,i = 0,然后 1,然后 2...等等...所以现在您可以检查每个组合。
关于algorithm - 在matlab中查找所有可能的排列/组合以等于特定的和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38022178/