title: How to compute de Bruijn sequences for non-power-of-two-sized alphabets?
body: <p>I'm trying to compute <a href="http://en.wikipedia.org/wiki/De_bruijn_sequence" rel="noreferrer">de Bruijn sequences</a> for alphabets which have a number of characters which is <em>not</em> a power of two.</p>
  
  <p>For alphabets with a 2^k characters, calculating de Bruijn sequences is easy: There are several simple rules, such as <a href="http://people.clarkson.edu/~aalhakim/Mypapers/PreferOpposite.pdf" rel="noreferrer">"Prefer Ones" and "Prefer Opposites"</a> which work for generating B(2,n). B(2^k,n) is exactly the same as B(2,kn), if you read the 1s and 0s as binary codes for the actual characters in your alphabet. E.g., you can interpret B(2,8n) as being over n-length sequences of bytes. </p>
  
  <p>Prefer Ones is quite simple: Write n zeros. Then, always write a one unless it would cause the repetition of an n-length string; otherwise, write a zero.</p>
  
  <p>Presently, I don't see how to generalize such rules to non-power-of-two-sized alphabets.</p>
  
  <p>There's a general method for calculating de Bruijn sequences via graphs: Let each n-length sequence generated by your alphabet be a node; put an edge from A to B iff the rightmost n-1 characters of A are the same as the leftmost n-1 characters of B. Label each edge with the last character of the string in the head vertex. Any <a href="http://en.wikipedia.org/wiki/Eulerian_path" rel="noreferrer">Eulerian path</a> through this graph will generate a de Bruijn sequence, and the peculiar construction we used guarantees that there will be at least one such path. We can use <a href="http://www.austincc.edu/powens/+Topics/HTML/05-6/05-6.html" rel="noreferrer">Fleury's Algorithm</a> to (nondeterministically) construct an Eulerian path:</p>
  
  <ol>
  <li>Choose a vertex.</li>
  <li>Leave that vertex via some edge and delete that edge, only choosing edges whose deletion would disconnect the vertex from the graph if there is no alternative.</li>
  <li>Append to your string the label of the edge you just deleted.</li>
  <li>Goto 2 until all edges are gone.</li>
  </ol>
  
  <p>The resulting string will be a de Bruijn sequence.</p>
  
  <p>This algorithm is somewhat more complex to implement than Prefer Ones. The simplicity of Prefer Ones is that one needs only to consult the output already generated to determine what to do. Is there a straightforward way to generalize Prefer Ones (or, possibly Prefer Opposites) to alphabets of non-power-of-two sizes?</p>