Iterator for Combination in C++


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(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
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;
   }
   string next() {
      idx++;
      return combs[idx - 1];
   }
   bool hasNext() {
      return !(idx == combs.size());
   }
};
main(){
   CombinationIterator ob("xyz", 2);
   cout << (ob.next()) << endl;
   cout << (ob.hasNext()) << endl;
   cout << (ob.next()) << endl;
   cout << (ob.hasNext()) << endl;
   cout << (ob.next()) << endl;
   cout << (ob.hasNext()) << endl;
}

Input

Initialize with “xyz” and 2, then call next() and hasNext() multiple times

Output

xy
1
xz
1
yz
0

Updated on: 30-Apr-2020

349 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements