Greplin Programming Challenge Level 3 (Matlab)
In Greplin challenge level 3 it is required to count the number of subsets which sum up to another element in list. See Greplin and Challenge Description and Python code. I also found this code in javascript, but I found it far less understoodable than Python.
My question is if there's some kind of Matlab command for finding all subsets of array, in similar way to the combinations library in python? Reffering to the challenge in your answer will be appreciated.
I tried some kind of writing my own code to it, but it obviously didn't work so well.
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, maxN开发者_StackOverflowum );
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;
You can use the function combnk
to find all possible combinations of n
items taken k
at a time. Using the competition's example:
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
The result:
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
To get the final answer, i.e., the number of subsets,
subsetSizes=cell2mat(cellfun(@size,matchingSubsets,'UniformOutput',false));
totalSubsets=sum(subsetSizes(:,1));
which gives totalSubsets=4
.
精彩评论