首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在matlab中找到等于特定和的所有可能的排列/组合

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

Stack Overflow用户
提问于 2016-06-25 05:11:04
回答 2查看 147关注 0票数 2

我被要求解决这个简单的问题,我的编程技能相当糟糕。这就是了

给定以下项目,找出所有服装项目的组合,使总成本恰好是100美元。

下面是我的代码:

代码语言:javascript
复制
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

我知道这段代码很原始,但我不知道如何处理……任何帮助都将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2016-06-25 06:49:26

看起来你在这个问题上有了一个很好的开端,我可以看到你在代码上有点困难。我会尽力帮你的。

代码语言:javascript
复制
tshirt=20; %price of tshirt
shorts=15; %price of shorts
socks=5; %price of socks 
solution=0;

好的开始,我们知道东西的价格。不过,看起来问题在for循环中,您想要检查所有的可能性……

代码语言:javascript
复制
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……等等。现在你可以检查每种组合了。

票数 2
EN

Stack Overflow用户

发布于 2016-06-25 07:57:33

您还可以用和的所有可能值填充一个3-D矩阵,因为您的范围非常小;然后,您只需查找等于too 100的值:

代码语言:javascript
复制
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]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38022178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档