Recursive generator in C++

前端 未结 5 1279
星月不相逢
星月不相逢 2021-02-06 11:13

I have a vector of size = N where each element i can have values from 0 to possible_values[i]-1. I want to do a function that iterates me through all those values.

I was

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 11:26

    Another implementation.

    PS: The printing of the values can be customized to look like the output from Python but I didn't think that was necessary to illustrate the algorithm to generate the output data.

    #include 
    #include 
    
    using namespace std;
    
    void print_values(vector > const& values)
    {
       for ( auto v1 : values)
       {
          for ( auto v : v1 )
          {
             cout << v << " ";
          }
          cout << "\n";
       }
    }
    
    vector > get_all_values(int size,
                                        vector::const_iterator iter)
    {
       vector > ret;
       if ( size == 1 )
       {
          for (int v = 0; v != *iter; ++v )
          {
             std::vector a = {v};
             ret.push_back(a);
          }
          return ret;
       }
    
       vector > prev = get_all_values(size-1, iter+1);
       for (int v = 0; v != *iter; ++v )
       {
          for ( vector& v1 : prev )
          {
             std::vector a = {v};
             a.insert(a.end(), v1.begin(), v1.end());
             ret.push_back(a);
          }
       }
    
       return ret;
    }
    
    vector > get_all_values(vector const& in)
    {
       return get_all_values(in.size(), in.begin());
    }
    
    int main()
    {
       vector a{2};
       vector b{2,3};
       vector c{2,3,2};
    
       cout << "----------\n";
       print_values(get_all_values(a));
       cout << "----------\n";
       print_values(get_all_values(b));
       cout << "----------\n";
       print_values(get_all_values(c));
       cout << "----------\n";
    
       return 0;
    }
    

    The output generated from running the program:

    ----------
    0
    1
    ----------
    0 0
    0 1
    0 2
    1 0
    1 1
    1 2
    ----------
    0 0 0
    0 0 1
    0 1 0 
    0 1 1
    0 2 0
    0 2 1
    1 0 0
    1 0 1
    1 1 0
    1 1 1
    1 2 0
    1 2 1
    ----------
    

提交回复
热议问题