MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   Greplin编程挑战3级(Matlab) (https://www.labfans.com/bbs/showthread.php?t=26715)

poster 2019-12-14 20:46

Greplin编程挑战3级(Matlab)
 
在Greplin挑战级别3中,需要计算总计为列表中另一个元素的子集的数量。请参阅[URL="http://challenge.greplin.com/"]Greplin[/URL]和[URL="https://github.com/krsanky/greplin-challenge/blob/master/level3.py"]挑战说明以及Python代码[/URL] 。我也在[URL="http://dmitrionsoftware.blogspot.com/2010/10/greplin-challenge-3-in-javascript_21.html"]javascript中[/URL]找到了[URL="http://dmitrionsoftware.blogspot.com/2010/10/greplin-challenge-3-in-javascript_21.html"]此代码[/URL] ,但是我发现它比Python难理解得多。

我的问题是,是否存在某种Matlab命令来查找数组的所有子集,类似于python中的组合库?回答您提出的挑战将不胜感激。

我尝试用某种方式编写自己的代码,但显然效果不佳。

Nums = [3 4 9 14 15 19 28 37 47 50 54 56 59 61 70 73 78 81 92 95 97 99]; % Nums = [1, 2, 3, 4, 6]; SubsetCount = 0; for Ind = 1:length(Nums) maxNum = Nums(Ind); s = setdiff( Nums, maxNum ); NumSubsetsCountToIt = NumSubsetsCount( s, maxNum); SubsetCount = SubsetCount + NumSubsetsCountToIt; end disp(SubsetCount); function NumSubsetsCountToIt = NumSubsetsCount( Nums, SumUpNum ) global OptionsToGetTo NumSubsetsCountToIt = 0; validNums = Nums; if sum(validNums)==SumUpNum NumSubsetsCountToIt = 1; else for Ind=length( validNums ):-1:1 outNum = validNums(Ind); s = setdiff(validNums, outNum ); NumSubsets = NumSubsetsCount( s, SumUpNum-outNum ); NumSubsetsCountToIt = NumSubsetsCountToIt+NumSubsets; end NumSubsetsCountToIt = floor((NumSubsetsCountToIt+1)/2); end OptionsToGetTo(2, b) = NumSubsetsCountToIt;

[B]回答:[/B]

您可以使用功能[URL="http://www.mathworks.com/help/toolbox/stats/combnk.html"]combnk[/URL]查找一次取k的n项目的所有可能组合。以比赛为例:

values=[1,2,3,4,6];%# test vector values=sort(values(:),'ascend');%#not needed here, but good to sort as indexing becomes easier in the end. matchingSubsets=cell(numel(values)-1,1);%we don't need the trivial case of j=j. So, 1 less cell. for i=2:numel(values) combinations=combnk(values,i); matchingSubsets{i-1}=combinations(sum(combinations(:,1:i-1),2)==combinations(:,i),:);%# this is where the sorting helps, as you now know that the last column is the max value. end 结果:

matchingSubsets{:} ans = Empty matrix: 0-by-2 ans = 2 4 6 1 3 4 1 2 3 ans = 1 2 3 6 ans = Empty matrix: 0-by-5 为了得到最终答案,即子集的数量,

subsetSizes=cell2mat(cellfun(@size,matchingSubsets,'UniformOutput',false)); totalSubsets=sum(subsetSizes(:,1)); 给出totalSubsets=4 。



[url=https://stackoverflow.com/questions/5439267]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 23:20

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.