因为我正在编写生成具有大量参数的SQL并将SQL记录到磁盘上的软件,所以我有一个不常见的要求(可能更多是好奇心):生成尽可能短的唯一参数名称。
参数名称遵循标识符命名规则,通常为:
[_]
)SQL生成代码知道总共有多少个标识符,因此可以根据整数生成名称。
答案 0 :(得分:1)
这最终比我预想的更困难,而且解决方案不那么优雅。
我对无效值进行了硬编码(从0
开始),因为它们很少,我每次尝试导出它们都变得复杂而缓慢。我很欣赏如何使这更优雅的想法。我也会发布CodeReview。
大多数数据库支持的参数少于2 ^ 16(实际使用的数字很荒谬),但在处理大于35027的数字时(也很荒谬)数字计算得出100万是一个很好的强制停止点。
public static String intToDatabaseIdentifier(int number)
{
if(number < 0 || number > 1000000)
throw new ArgumentOutOfRangeException("number");
if(number > 25 && number <= 25 + 10) // Skip 0-9 (modified base 36)
number += 10;
if(number > 971 && number <= 971 + 360) // Skip 0a-09 (modified base 36)
number += 360;
if(number > 35027 && number <= 35027 + 12960) // Skip 0aa-099 (modified base 36)
number += 12960;
var stack = new Stack<char>();
// Base 36 starting with letters rather than numbers
const string characters = "abcdefghijklmnopqrstuvwxyz0123456789";
while(number >= 0) {
stack.Push(characters[number % 36]);
number = number / 36 - 1;
}
return new String(stack.ToArray());
}
从0开始的结果:
a b c d e f g h i j k l m n o p q r s t u v w x y z
aa ab ac ad ae af ag ah ai aj aa ab ac ad ae af ag ah ai aj ak al am an ao
ap aq ar as at au av aw ax ay az a0 a1...
答案 1 :(得分:0)
上面的代码会产生冲突。固定代码没有冲突和幻数。
public static String intToDatabaseIdentifier(int number)
{
const string abcFirst = "abcdefghijklmnopqrstuvwxyz";
const string abcFull = "abcdefghijklmnopqrstuvwxyz0123456789";
if (number < 0 || number > 1000000)
throw new ArgumentOutOfRangeException("number");
var stack = new Stack<char>();
//Get first symbol. We will later reverse string. So last - will be first.
stack.Push(abcFirst[number % abcFirst.Length]);
number = number / abcFirst.Length;
//Collect remaining part
while (number > 0)
{
int index = (number - 1) % abcFull.Length;
stack.Push(abcFull[index]);
number = (number - index) / abcFull.Length;
}
//Reversing to guarantee first non numeric.
return new String(stack.Reverse().ToArray());
}
答案 2 :(得分:0)
aa, ba, ca
代替aa, ab, ac
:
(使用String.Concat(ToParamName(i))
调用)
// Starts with aa, ba, ba... instead of a, b, c. Probably wouldn't be hard
// to fix but I abandoned this method because it's annoying to call using
// string.Concat(...)
public static IEnumerable<char> ToParamName(int number) {
const string characters = "abcdefghijklmnopqrstuvwxyz0123456789";
yield return characters[number % 26];
number = number / 26;
do {
yield return characters[number % 36];
number = number / 36 - 1;
} while(number >= 0);
}
// Starts with a, b, c...aa, ba, ba but has collisions starting around 960
public static IEnumerable<char> ToParamName(int number) {
const string characters = "abcdefghijklmnopqrstuvwxyz0123456789";
yield return characters[number % 26];
number = number / 26;
while(number > 0) {
yield return characters[number % 36];
number = number / 36 - 1;
}
}
我更喜欢以更自然的顺序返回结果,例如a..z, aa, ab, ac...a9
(嘿,我没有声称我纯粹是实用的),但我忘了在原帖中提到。帖木儿的答案涵盖了所有原始要求,因此我将其标记为正确。
我将+1给出一个产生所述结果的答案。