2

I want to generate a algorithm in which I want to get the next string in lexicographically order.

Suppose I want to generate a list of length 26 then it is

['a','b'....'z']

Now suppose I want to generate a list of length 260 then it is

['a0','a1','a2'...'a9','b1'....'z0'....'z9']

This type of algorithm have max-limit. But I don't want such type of limitations. It may be 10000 or 1 millions.

Requirement

Algorithm should work in such a way that previously string is passed as argument generate by it. And it should produce the next string in lexicographically order. And I do not want to use timestamp (1503314045645)

Thanks

abhaygarg12493
  • 1,565
  • 2
  • 20
  • 40
  • Since incrementing the string isn't as useful in real life, also see: https://stackoverflow.com/questions/43356549/auto-incrementing-alphanumeric-sequence/43358781#43358781 – Matt Timmermans Aug 21 '17 at 12:04
  • 1
    what is the character set? Also, in 1st case, y not `['a', 'aa',...,'aaa...aaa(26 times)']`? (I believe `aa` is lexically smaller than `b`) – vish4071 Aug 21 '17 at 18:17

1 Answers1

0

What about using base 36 formatted integers? It looks like this in java:

String next(String prev) {
  if(prev==null) {
    return "0";
  }
  return Integer.toString(Integer.parseInt(prev, 36), 36);
}

Actually it's even better if you you use a simple integer for storing the value, and simply increase it every time you need the next value and format the integer using base 36 into a string:

Integer.toString(++value, 36);

In this solution the numbers are before the letters in the output, so you will get the following tokens: a7,a8,a9,aa,ab, ... ax,ay,az,b0,b1 ... zx,zy,zz,100,101

If you want letters first or want any specific order or extra characters, then use the solution behind Matt Timmermans' link.

Selindek
  • 3,269
  • 1
  • 18
  • 25