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, 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;
You can use the function
combnkto find all possible combinations ofnitems takenkat a time. Using the competition’s example:The result:
To get the final answer, i.e., the number of subsets,
which gives
totalSubsets=4.