0

Say you have the finite alphabet $\{a,b,c,d,e,f,g\}$ and an enumeration of finite strings over it by the shortlex order (length-lexicographic ordering), starting with the empty string, i.e., $\epsilon, a, b, c, d, e, f, g,$ $aa, ab, ac, \cdots,$ $gg, \cdots, aaa, aab, aac,$ $\cdots, ggg, \cdots$.

What's the most efficient algorithm to get a string from that sequence by its index? For example, given 9, we should get $ab$.

Basically, I'm looking for a fast procedure that takes an integer $x$ and returns the $x$-th string from a list of strings enumerated over a fixed, finite alphabet.

John L.
  • 38,985
  • 4
  • 33
  • 90
Quavo
  • 1
  • 1

1 Answers1

1

Easier problem: Suppose you want the $i$th string, from all length-$k$ strings over that template. Can you find the $i$th string? This is easy. I'll let you figure out how to do that.

Your problem: Suppose you want the $i$th string. Well, there are $1+6+6^2+\dots+6^k$ strings of length $\le k$ over this alphabet. So, find the smallest $k$ such that $i \le 1+6+6^2+\dots+6^k$; then you know that the output needs to be a length-$k$ string. Let $j=i-(1+6+6^2+\dots+6^{k-1})$; and find the $j$th string, from all length-$k$ strings.

I'm guessing you can take it from here.

rici
  • 12,020
  • 21
  • 38
D.W.
  • 159,275
  • 20
  • 227
  • 470