Binomial coefficients with a twist: How could I write this in Matlab?

1 view (last 30 days)
Hi,
Here is an algorithm someone suggested me to use in order to generate binomial coefficients but with a specific constraint.
First, the pseudocode:
combs(index,multiset,k,result):
if length of result == k:
output result
return
if length of result + length of multiset - index < k:
return
for j in multiset[index]:
combs(index + 1,multiset,k,result with multiset[index][j] added)
combs(index + 1,multiset,k,result)
Then, the person gave me a JavaScript example:
function combs(i,multiset,k,result){
if (result.length == k){
console.log(result);
return;
}
if (result.length + multiset.length - i < k)
return;
for (var j=0; j<multiset[i].length; j++){
_result = result.slice();
_result.push(multiset[i][j]);
combs(i + 1,multiset,k,_result);
}
combs(i + 1,multiset,k,result);
}
combs(0,[["1.A","8.A"],["2.B","5.B"],["3.C","7.C"],["4.D","6.D"]],4,[]);
You may use this website: https://repl.it/languages/javascript in order to run the Javascript code and see the result.
Now, I've tried to implement this recursive function in Matlab, but failed. Here is what I have tried:
function result = combs(index,multiset,k,temp)
result = temp;
% if length of result == k:
if (size(temp,1) == k)
result = temp;
return;
end
% if index > length of multiset:
% return
if ((size(multiset,1) + size(temp,1) - index+1) < k)
result = temp;
return;
else
% else:
% for j in multiset[index]:
% combs(index + 1,multiset,k,result with multiset[index][j] added)
for j = 1:size(multiset,2)
temp = result;
temp(end+1,j) = multiset(index,j);
temp = combs(index + 1, multiset, k, temp);
end
temp = combs(index + 1, multiset, k, temp);
end
result = temp;
end
If anybody has the knowledge to properly port this to Matlab, I would be very glad! :)

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!