我有员工数据,每个员工都有地址信息。我需要为邮政编码(5个字符)和地址line1 (35个字符)生成唯一的9位(数字或字母数字)值,这是表示位置的唯一值。它也称为"Wrap number“。
如下图所示,当两个员工的地址相同时,则包装编号应相同,否则应分配新值。
哪种算法最适合生成9位数的唯一值?
另外,我需要用Java编写程序。

发布于 2017-11-01 04:13:50
你的要求是不可能的。不,真的,不可能。
您有一个5位的邮政编码,可以用17位进行编码。那么你有35个字符的文本。假设您将其限制为大写和小写字母,加上数字和特殊字符。图96个可能的字符,或每个字符大约6.5位。所以:
35 * 6.5 = 227.5 ~ 228 bits因此,您有多达245位的信息,并且您想要创建一个“唯一的”9字符代码。您的9个字符的代码只占72位。你无法将228比特的信息打包成72比特而不复制。参见Pigeonhole principle。
更好的解决方案是为每个员工分配一个序列号。如果您想要生成9个字符的代码,那么使用一种技术来混淆数字,并使用基数36(数字和大写字母)或类似的东西对它们进行编码。我在我的博客文章How to generate unique "random-looking" keys中解释了如何做到这一点。
发布于 2017-10-31 19:36:42
简单的想法是使用众所周知的散列算法,这些算法已经在Java中实现了。
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,因为这些哈希函数会带来冲突。
发布于 2017-10-31 18:56:51
我的想法是:
String str = addressLine + postalCode;
UUID uid = UUID.nameUUIDFromBytes(str.getBytes());
return makeItNineDigits(uid);其中,makeItNineDigits是根据您的喜好对UUID字符串表示的某种简化。:)这可能是uid.ToString().substring(0, 9)。或者,您可以获取两个长值getLeastSignificantBits和getMostSignificantBits,并从它们创建一个9位数的值。
https://stackoverflow.com/questions/47032996
复制相似问题