Related to this question, I am wondering the algorithms (and actual code in java/c/c++/python/etc., if you have!) to generate all combinations of r elements for a list with m elements in total. Some of these m elements may be repeated.
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here is a recursion that I believe is closely related to Jean-Bernard Pellerin’s algorithm, in Mathematica.
This takes input as the number of each type of element. The output is in similar form. For example:
Function:
Use:
{{0, 0, 0, 4}, {0, 0, 1, 3}, {0, 1, 0, 3}, {0, 1, 1, 2}, {0, 2, 0, 2}, {0, 2, 1, 1}, {1, 0, 0, 3}, {1, 0, 1, 2}, {1, 1, 0, 2}, {1, 1, 1, 1}, {1, 2, 0, 1}, {1, 2, 1, 0}, {2, 0, 0, 2}, {2, 0, 1, 1}, {2, 1, 0, 1}, {2, 1, 1, 0}, {2, 2, 0, 0}}An explanation of this code was requested. It is a recursive function that takes a variable number of arguments. The first argument is
k, length of subset. The second is a list of counts of each type to select from. The third argument and beyond is used internally by the function to hold the subset (combination) as it is constructed.This definition therefore is used when there are no more items in the selection set:
If the total of the values of the combination (its length) is equal to
k, then return that combination, otherwise return an empty set. (+cis shorthand forPlus[c])Otherwise:
Reading left to right:
Joinis used to flatten out a level of nested lists, so that the result is not an increasingly deep tensor.f[k, {r}, c, #] &calls the function, dropping the first position of the selection set (x), and adding a new element to the combination (#)./@ 0 ~Range~ Min[x, k - +c])for each integer between zero and the lesser of the first element of the selection set, andkless total of combination, which is the maximum that can be selected without exceeding combination sizek.