I need to generate unique strings starting from int number (id). The length must be proportionally incremental, so for tiny ids I have to generate unique strings of four characters. For big ids I have to generate strings much more complex, with growing size when needed (max 8 digit) in order to accomplish the uniqueness. All this procedure must be done with two opposite functions:
from id -> obtain string
from string -> obtain id
Unique strings must be composed by numbers and characters of a specific set (379CDEFHKJLMNPQRTUWXY)
Is there a well know algorithm to do this? I need to do this in c# or better in tsql. Ideas are also appreciated.
Edit
I have "simply" the need to encode (and than decode) the number. I've implemented this routines for my alphabet (21 symbols length): Encode:
public static String BfEncode(long input)
{
if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
char[] clistarr = BfCharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 21]);
input /= 21;
}
return new string(result.ToArray());
}
And decode:
public static Int64 BfDecode(string input)
{
var reversed = input.ToLower().Reverse();
long result = 0;
int pos = 0;
foreach (char c in reversed)
{
result += BfCharList.IndexOf(c.ToString().ToUpper()) * (long)Math.Pow(21, pos);
pos++;
}
return result;
}
I've generated example strings in a loop starting from 10000 to 10000000 (!). Starting from 10K I can generate strings of 4 digits length. After the generation I've put all the strings in a list and checked for uniqueness (I've done it with parallel foreach...). At the number 122291 the routine thrown an exception because there is a duplicate! Is it possibile? The base conversion to a custom alphabet is not a good solution?