0

我必须生成 16 个字符串,每月大约 1,00,000 个。它们应该不会在多次运行中重复(每月一次,每月一次)。实现这一目标的最佳方法是什么?使用哈希函数是个好主意吗?字符串只能有 AZ 和 0-9。这将使用 C# 来完成。编辑:字符串应该是随机的。因此,保留一个简单的计数器不是一种选择。

4

3 回答 3

1

由于您仅限于 16 个字母数字字符,因此 GUID 可能不是一个选项 - 它要求完整的 128 位是唯一的,虽然这将生成一个 16 个字符的字符串,但它不一定适合字母数字约束。

您可以有一个简单的计数器并返回 MD5 哈希的最后 64 位,并每次检查唯一性。

//parse out hex digits in calling code
static long NextHash(HashSet<long> hashes, int count)
{
    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
    long l = BitConverter.ToInt64(md5.ComputeHash(IntToArray(count)));
    if(!hashes.Contains(l)){
        hashes.Add(l);
        return l;
    } else return -1; //check this in calling code for failure
}
static byte[] IntToArray(int i)
{
    byte[] bytes = new byte[4];
    for(int j=0;j<4;j++){
    bytes[j] = (byte)i;
    i>>=8;    
    }
}

您可以为 GUIDS 做类似的事情,但我不知道当您只查看子字符串时发生冲突的可能性有多大。MD5 哈希具有“出现”更随机的优势,如果这完全相关的话。

于 2013-06-10T08:48:47.013 回答
0

我不知道这是否满足你,但我想出了那样的东西

static List<string> generate(int count)
{
    List<string> strings = new List<string>();
    while (strings.Count < count)
    {
        Guid g = Guid.NewGuid();                
        string GuidString = g.ToString();
        GuidString = GuidString.Replace("-", "");
        GuidString = GuidString.Remove(16);
        if (!strings.Contains(GuidString))
            strings.Add(GuidString);
    }
    return strings;
}
于 2013-06-10T07:50:09.260 回答
0

您尚未指定语言。

PHP,

http://php.net/manual/en/function.uniqid.php

echo rand(0,999).uniqid();
rand(0,999) = 3 characters randomly
uniqid() = 13 randomly characters 
于 2013-06-10T06:52:18.950 回答