gpt4 book ai didi

algorithm - 在matlab中找到所有可能的排列/组合以等于特定和

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:41:35 24 4
gpt4 key购买 nike

我被要求解决这个简单的问题,我的编程水平相当惨。在这里,

给定以下项目,找到所有服装项目的组合,使总成本恰好为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com