首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串生成9位唯一值

从字符串生成9位唯一值
EN

Stack Overflow用户
提问于 2017-10-31 18:24:09
回答 4查看 2.3K关注 0票数 2

我有员工数据,每个员工都有地址信息。我需要为邮政编码(5个字符)和地址line1 (35个字符)生成唯一的9位(数字或字母数字)值,这是表示位置的唯一值。它也称为"Wrap number“。

如下图所示,当两个员工的地址相同时,则包装编号应相同,否则应分配新值。

哪种算法最适合生成9位数的唯一值?

另外,我需要用Java编写程序。

EN

回答 4

Stack Overflow用户

发布于 2017-11-01 04:13:50

你的要求是不可能的。不,真的,不可能。

您有一个5位的邮政编码,可以用17位进行编码。那么你有35个字符的文本。假设您将其限制为大写和小写字母,加上数字和特殊字符。图96个可能的字符,或每个字符大约6.5位。所以:

代码语言:javascript
复制
35 * 6.5 = 227.5 ~ 228 bits

因此,您有多达245位的信息,并且您想要创建一个“唯一的”9字符代码。您的9个字符的代码只占72位。你无法将228比特的信息打包成72比特而不复制。参见Pigeonhole principle

更好的解决方案是为每个员工分配一个序列号。如果您想要生成9个字符的代码,那么使用一种技术来混淆数字,并使用基数36(数字和大写字母)或类似的东西对它们进行编码。我在我的博客文章How to generate unique "random-looking" keys中解释了如何做到这一点。

票数 2
EN

Stack Overflow用户

发布于 2017-10-31 19:36:42

简单的想法是使用众所周知的散列算法,这些算法已经在Java中实现了。

代码语言:javascript
复制
private static long generateIdentifier(final String adrLine, final String postCode) {
    final String resultInput = adrLine + postCode;

    //do not forget about charset you want to work with
    final byte[] inputBytes = resultInput.getBytes(Charset.defaultCharset());
    byte[] outputBytes = null;

    try {
        //feel free to choose the encoding base like MD5, SHA-1, SHA-256
        final MessageDigest digest = MessageDigest.getInstance("SHA-256");
        outputBytes = digest.digest(inputBytes);
    } catch (NoSuchAlgorithmException e) {
        //do whatever you want, better throw some exception with error message
    }

    long digitResult = -1;
    if (outputBytes != null) {
        digitResult = Long.parseLong(convertByteArrayToHexString(outputBytes).substring(0, 7), 16);
    }

    return digitResult;
}

//this method also may be useful for you if you decide to use the full result
// or you need the appropriate hex representation
private static String convertByteArrayToHexString(byte[] arrayBytes) {
    final StringBuilder stringBuffer = new StringBuilder();
    for (byte arrByte: arrayBytes) {
        stringBuffer.append(Integer.toString((arrByte & 0xff) + 0x100, 16)
                .substring(1));
    }
    return stringBuffer.toString();
}

我建议您不要使用MD5和SHA1,因为这些哈希函数会带来冲突。

票数 1
EN

Stack Overflow用户

发布于 2017-10-31 18:56:51

我的想法是:

代码语言:javascript
复制
String str = addressLine + postalCode;
UUID uid = UUID.nameUUIDFromBytes(str.getBytes());
return makeItNineDigits(uid);

其中,makeItNineDigits是根据您的喜好对UUID字符串表示的某种简化。:)这可能是uid.ToString().substring(0, 9)。或者,您可以获取两个长值getLeastSignificantBitsgetMostSignificantBits,并从它们创建一个9位数的值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47032996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档