title: Enumerate all words of a language in a sequence
body: <p>I've successfully enumerated all words for the languages Σ={a*} and Σ={a^n b^n} with following approach:</p>
  
  <pre><code>public class AStar {
      public static int n = 0;
      public static void main(String[] args) {
          for(int i=0;i&lt;10;i++){
              System.out.println(next());
          }
      }
  
      public static String next(){
          String as="" , bs="";
          String s= "";
          for(int i=0; i&lt;n; i++) {
              as+="a"; bs+="b";
              s=as+bs;
          }
          n++;
          return s;
      }
  }
  </code></pre>
  
  <p>On each call to next(), it prints a word like this(using for loop to invoke next multiple times):
  ab, aabb, aaabbb, ......, a^n b^n</p>
  
  <p><strong>Current Problem</strong></p>
  
  <p>Now I'm working on a similar class that could enumerate words of language Σ*={a,b}</p>
  
  <p>On each call to next(), it should return a new word that comes after the previously returned word, for instance, it should return these words: </p>
  
  <p>'', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', ...... upto words having n-literals</p>
  
  <p>The ordering of literals does not matter, I've tried this logic but no success so far</p>
  
  <pre><code>public class ABStar {
      static int col=0, row=0, cur=0, rlen=0, flag=1, set=0;
      public static void main(String[] args) {
          for(int i=0;i&lt;5;i++){
              System.out.println(next());
          }
      }
      public static String next(){
          String s="";
          row = 1 &lt;&lt; col;
          rlen = row/2;
          for(int i=1; i&lt;=row; i++){
              for(int j=1 ; j&lt;=col ; j++){
                  if(col==1 &amp;&amp; flag ==1){
                      return s+="a";
                  }
                  else if(col==1 &amp;&amp; flag ==2){
                      return s+="b";
                  }
                  rlen --;
                  if(rlen==0){
                      flag = 3-flag;
                      rlen=row/2;
                  }
              }
          }
          col++;
          return "";
      }
  }
  </code></pre>
  
  <p>I'm using flags col(columns), row(rows), cur(current), flag(1 for a's, 2 for b's), rlen (length of rows for each flag), I'm using these attributes to preserve the states between different calls.</p>
  
  <p>I've tried to solve this problem with almost 2 dozen logics but all in vain, please help me solve this problem, I'll be highly obligated.</p>