gpt4 book ai didi

algorithm - 创建顺序固定大小的 base 36 id

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:47 25 4
gpt4 key购买 nike

我想创建一个函数,它将为我提供固定大小的 6 个字符的字母数字 ID,并要求第一个和最后一个字符必须是字母。

我希望它们按顺序生成。我认为使用 base36 是处理 [0-9A-Z] 字母表的方法,但是我不太确定如何确保它们始终为 6 个字符长,开头和结尾都有一个 alpha。

例如,如果我按顺序创建 ID 并从 0 开始,我将得到输出 0,因为 0 在两个基数中是相同的。

有谁知道可以在这里提供帮助的高效算法吗?

谢谢

最佳答案

您可以使用标准算法将 int 转换为 base36 字符串,通过对基数取模然后将余数除以基数来一次提取一个数字,但是为第一个和最后一位:

例如在 Java 中:

static String getId(int id)
{
String s = "";
for(int i = 0; i < 6; i++)
{
// compute the digit using modulo arithmetic using base 26
// for first and last character and base 36 for others
int digit;
if((i == 0) || (i == 5))
{
digit = (id % 26) + 10;
id /= 26;
}
else
{
digit = id % 36;
id /= 36;
}

// add the digit to the string:
if(digit < 10)
s = (char)('0' + digit) + s;
else
s = (char)('A' + (digit - 10)) + s;
}
return s;
}

一共有 26*36*36*36*36*26 = 1135420416 种可能,也就是说你只需要一个 32 位整数来存储它们。

关于algorithm - 创建顺序固定大小的 base 36 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com