我被要求解决这个简单的问题,我的编程技能相当糟糕。这就是了
给定以下项目,找出所有服装项目的组合,使总成本恰好是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我知道这段代码很原始,但我不知道如何处理……任何帮助都将不胜感激。
发布于 2016-06-25 06:49:26
看起来你在这个问题上有了一个很好的开端,我可以看到你在代码上有点困难。我会尽力帮你的。
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……等等。现在你可以检查每种组合了。
发布于 2016-06-25 07:57:33
您还可以用和的所有可能值填充一个3-D矩阵,因为您的范围非常小;然后,您只需查找等于too 100的值:
price=100;
tshirt=20; %price of tshirt
shorts=15; %price of shorts
socks=5; %price of socks
[X,Y,Z]=meshgrid(1:floor(100/tshirt),1:floor(100/shorts),1:floor(100/socks));
SumsMatrix=tshirt*X+shorts*Y+socks*Z;
linIds=find(SumsMatrix==100);
[idx,idy,idz]=ind2sub(size(SumsMatrix),linIds);
comb=[idx idy idz]https://stackoverflow.com/questions/38022178
复制相似问题