To make it more specific, I need an algorithm (recursive or not) that, given a integer n and a matrix as input, will return me all of the combinations that will have:
1) At least 1 object from each line
2) Will have n objects total
I feel I could solve this easier if I just tried all combinations and use the ones that have n objects and 1 from each line, but I believe that the algorithm can be a lot more efficient than that.
I have also successfully coded an algorithm that will return all combinations of 1 object per line, but couldn’t expand it to more. I’ve been coding in Python, but any language is fine. Extra points for consideration that python passes objects per reference. =)
Assume the matrix is squared. If anyone wants to know why, this is part of a more complex graph algorithm I’m trying to solve.
Thanks all!
Thanks for all the answers, they were close to what I was looking for. I managed to do it under Python (so I didn’t check the results posted here), my problem was actually Python passing reference vs copy in function calls. I thought a shallow copy would have been enough, but apparently I needed a deep copy (haven’t thought it through why shallow wasn’t enough).
This is how I did it:
PS1: Graphs here are dictionaries of lists. n_edges is the number of edges to be picked from the graph
PS2: Size calculation here is pretty inefficient, haven’t taken time to fix it yet.
PS3: In order to iterate orderly over a dictionary, I created two lists: a list-of-lists representation of the graph (lol) and an index array that matches it (lolindex).
PS4: Adapted to fit the question I posted, the real method I used has more problem specific code to it. Haven’t tested the code in the way I put it here.