I am looking for an algorithm to find all combinations of K values to n items.
Example:
K values are [R,B] & N is 2 so i get {RR, RB, BR, BB} 2*2 = 4 ways
K values are [R,B] & N is 3 so i get {RRR, RRB, RBB, RBR, BRR, BRB, BBR, BBB} 2*2*2 = 8 ways
I need to find out the generic algorithm to find all possible ways in which K items can be arranged in N slots. (repeat is allowed)
Another example would be:
K values are [R,G,B] & N is 5 so i need to find 3^5 = 81 combinations.
This problem lends itself exceptionally well to a recursive solution.
The solution in the general case is clearly formed by taking the solution for
N - 1, and then prepending each of your set’s elements in turn to the results. In pseudocode:This could be implemented recursively in Java, but you’d run into stack overflow errors for moderately large values of
n; and I also suspect the JIT compiler is less effective at optimising recursive algorithms so performance would suffer.However, recursive algorithms can always be converted into a loop equivalent. In this case it might look something like:
This works (I hope!) similarly to the recursive method – at each iteration it “saves” the current progress (i.e. the result for
n-1) topreviousResults, then just iterates over the options in turn, to get the result of prepending them to the previous results.It would be interesting to see the effects of passing the recursive solution through any automatic recursion-to-iterative algorithms, and compare both the readability and performance to this hand-created one. This is left as an exercise for the reader.