How to generate all variations with repetitions of a string?

前端 未结 3 428
南方客
南方客 2020-12-16 06:04

I want to generate all variations with repetitions of a string in C++ and I\'d highly prefer a non-recursive algorithm. I\'ve come up with a recursive algorithm in the past

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 06:09

    STL like function for next_variation. Accept iterators of any container of number like type. You can use float/doubles also. Algorithm it self is very simple. Requirement for iterator is to be only forward. Even a std::list<...> can be used.

    template
     bool next_variation
      (
           _Titerator const& _First
         , _Titerator const& _Last
         , _Tnumber const& _Upper
         , _Tnumber const& _Start = 0
         , _Tnumber const& _Step  = 1
      )
      {
       _Titerator _Next = _First;
       while( _Next  != _Last )
        {
          *_Next += _Step;
         if( *_Next < _Upper )
          {
           return true;
          }
         (*_Next) = _Start;
         ++_Next;
        }
       return false;
      }
    
    int main( int argc, char *argv[] )
     {
      std::string s("aaaa");
      do{
          std::cout << s << std::endl;
      }while (next_variation(s.begin(), s.end(), 'c', 'a'));
    
      std::vector< double > dd(3,1);
      do{
       std::cout << dd[0] << "," << dd[1] << "," << dd[2] << ","  << std::endl;
      }while( next_variation( dd.begin(), dd.end(), 5, 1, 0.5 ) );
    
      return EXIT_SUCCESS;
     }
    

提交回复
热议问题