Given a collection of piles of different heights, how do I select all possible combinations?

advertisements

Input: total cost.

Output: all the combinations of levels that give the desired cost.

Every level of each stack costs a different amount (level 1 in stack 1 doesn't cost the same as level 1 in stack 2). I have a function that converts the level to the actual cost based on the base cost (level 1), which I entered manually (hard coded).

I need to find the combination of levels that give me the inputed cost. I realize there are more than one possible solutions, but I only need a way to iterate trough every possibility.

Here is what I need:

input = 224, this is one of the solutions:


I'm making a simple program that needs to select levels of different stacks and then calculate the cost, and I need to know every possible cost that exists... Each level of each stack costs a different amount of money, but that is not the problem, the problem is how to select one level for each stack.

I probably explained that very vaguely, so here's a picture (you'll have to excuse my poor drawing skills):

So, all stacks have the level 0, and level 0 always costs 0 money.

Additional info:

  • I have an array called "maxLevels", length of that array is the number of stacks, and each element is the number of the highest level in that stack (for example, maxLevels[0] == 2).
  • You can iterate from the 1st level because the level 0 doesn't matter at all.
  • The selected levels should be saved in an array (name: "currentLevels) that is similar to maxLevels (same length) but, instead of containing the maximum level of a stack, it contains the selected level of a stack (for example: currentLevels[3] == 2).
  • I'm programming in C++, but pseudocode is fine as well.
  • This isn't homework, I'm doing it for fun (it's basically for a game).

I'm not sure I understand the question, but here's how to churn through all the possible combinations of selecting one item from each stack (in this case 3*1*2*3*1 = 18 possibilities):

void visit_each_combination(size_t *maxLevels, size_t num_of_stacks, Visitor &visitor, std::vector<size_t> &choices_so_far) {
    if (num_of_stacks == 0) {
        visitor.visit(choices_so_far);
    } else {
        for (size_t pos = 0; pos <= maxLevels[0]; ++pos) {
            choices_so_far.push_back(pos);
            visit_each_combination(maxLevels+1, num_of_stacks-1, visitor, choices_so_far);
            choices_so_far.pop_back();
        }
    }
}

You can replace visitor.visit with whatever you want to do with each combination, to make the code more specific. I've used a vector choices_so_far instead of your array currentLevels, but it could just as well work with an array.