Iterator for Combination in C++

C++Server Side ProgrammingProgramming

Suppose we have to design an Iterator class, that consists of few operations −

  • Define a constructor that takes a string characters of sorted distinct lowercase English letters and a number combinationLength as parameter.
  • Define a function next() that returns the next combination of length combinationLength in alphabetic order.
  • Define another function hasNext() that returns True if and only if there exists a next combination.

So if the input is like −

CombinationIterator iterator = new CombinationIterator("xyz", 2);
iterator.next(); // returns "xy"
iterator.hasNext(); // returns true
iterator.next(); // returns "xz"
iterator.hasNext(); // returns true
iterator.next(); // returns "yz"
iterator.hasNext(); // returns false

To solve this, we will follow these steps −

  • Create an array comb of strings, and index idx
  • Define a method makeCombs(), this will take string s, integer variable l, a temp string, that is initially empty, and start, that is initially 0. This is defined as follows −
  • if size of temp = l, then insert temp into comb and return
  • for i in range start to size of s
    • makeCombs(s, l, temp + s[i], i + 1)
  • printVector() method will take the array of string as input, this will display the elements of that array
  • Define the constructor as follows: this will take string c and cl,
  • call makeCombs(c, cl), set idx := 0
  • The next() method will increase idx and return comb[idx - 1]
  • the hasNext() method will return true if idx is not same as size of comb, otherwise false.

Example

Let us see the following implementation to get better understanding −

class CombinationIterator {
   public:
   vector <string> combs;
   int idx;
   void makeCombs(string s, int l, string temp ="", int start = 0){
      if(temp.size() == l){
         combs.push_back(temp);
         return;
      }
      for(int i = start; i < s.size(); i++){
         makeCombs(s, l, temp + s[i], i + 1);
      }
   }
   void printVector(vector <string> v){
      for(int i = 0; i < v.size(); i++){
         cout << v[i] << "\n";
      }
      cout << endl;
   }
   CombinationIterator(string c, int cl) {
      makeCombs(c, cl);
      idx = 0;
      //printVector(combs);
   }
   string next() {
      idx++;
      return combs[idx - 1];
   }
   bool hasNext() {
      return !(idx == combs.size());
   }
};
/**
* Your CombinationIterator object will be instantiated and called as such:
* CombinationIterator* obj = new CombinationIterator(characters, combinationLength);
* string param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/

Input

["CombinationIterator","next","hasNext","next","hasNext","next","hasNext"]
[["xyz",2],[],[],[],[],[],[]]

Output

[null,"xy",true,"xz",true,"yz",false]
raja
Published on 17-Mar-2020 12:06:14
Advertisements