Generate all possible settings

Consider a situation in which there are n independent decision, each of which has some discrete set of choices (possibly different). That is, there may be b_0 choices for decision 0, and b_1 choices for decision 1, and so on. We assume that each individual decision is denoted as an index starting at 0.

We are interested in enumerating lexicographically through all possible settings for those decisions. For example, if there are three decisions, with the number of options respectively being (3,2,3) then there are 18 possible settings, namely

0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2

Note that in the special case when all decisions have the same number of choices, then this enumeration is precisely a "base b" counter, and in the special case where that base is 2, this can be used to enumerate through all possible subsets (with decision 0 being a chosen element and decision 1 being non-chosen to get lexicographical subsets).


C++

We suggest the following function, having a similar design to our next_combination approach. In this case, there should be two coordinates sequences, one given the current settings for the decisions and the other giving the respective number of choices for each decision. The former should always be initialized to all decisions having setting 0.

template <typename BI>
bool next_setting(BI first, BI last, BI lastLimit) {
  do {
    if (*(--last) < *(--lastLimit) - 1) {         // punctuate this correctly!
      (*last)++;
      return true;
    }
    (*last) = 0;                     // reset this digit
  } while (last != first);

  return false;                      // failed
}

Here is a typical example, in which all decisions have 3 choices.

  vector<int> decisions(n,0);   // all zeros
  vector<int> limits(n,3);      // 3 choices for each decision
  do {
     // process current setting
  } while ( next_setting(decisions.begin(), decisions.end(), limits.end()) );

Java

Can do same thing, although will need to rewrite it properly to match the conventions for iterating collections.
Michael Goldwasser
Last modified: Friday, 22 October 2010