【问题标题】:Finding all possible permutations/combinations to equal a specific sum in matlab在matlab中查找所有可能的排列/组合以等于特定总和
【发布时间】:2016-06-24 21:11:04
【问题描述】:

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

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

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

【问题讨论】:

  • 这基本上是硬币找零的问题,它会是一个好的开始搜索。
  • 最终等式应该看起来像 i * tshirt+j * shorts+k * socks==100。我不记得 Matlab 但通常你应该有: if (i * tshirt+j * shorts+k * socks==100) solution=solution+1

标签: algorithm matlab combinations


【解决方案1】:

看起来您在这个问题上已经有了一个良好的开端,我可以看到您在处理代码方面有点吃力。我会尽力帮助你的。

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...等等...所以现在您可以检查每个组合。

【讨论】:

    【解决方案2】:

    您还可以使用总和的所有可能值填充 3-D 矩阵,因为您的范围非常小;然后,您只需查找也相等的值 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多