有没有更好的方法来散列由128个合法ASCII字符中的任何一个组成的字符串的排列



假设任何两个相互置换的字符串都被认为是相同的(例如(ABACD,BDCAA(和(ABACD、DBACA(应该散列到HashMap的同一个桶中(。字符串仅由128个合法ASCII字符中的任何一个组成。有没有更好的哈希函数可以在保持HashMap较小的同时最大限度地减少冲突?

此外,还有什么方法可以进一步优化代码吗?主要目标是尽可能减少运行时间。

该方法接收一个文件,该文件包含一组文本行,每行代表一个条目。文件中的第一行表示条目的总数。它将计算包含相同多集的条目对的总数。

输入文件包含的内容示例:7.BCDEFGH算盘BDCEFBDCAADBACA达巴卡DABAC

它应该输出:6

这六对是:(算盘,BDCAA((ABACD,DBACA((阿巴德,达巴克((BDCAA,DBACA((BDCAA,DABAC((DBACA,DABAC(

散列发生的部分:

long hash = 1;
while (c != 10) {
hash *= PRIMES[c];
c = reader.read();
}
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
public class Speed {
private static final int[] PRIMES = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719};
public int processData(String filename){
try {
Reader reader = new Reader(filename);
int size = Integer.parseInt(reader.readLine());
HashMap<Long, Integer> hm = new HashMap<>(size / 2);
int total = 0;
while (true) {
int c = reader.read();
if (c == -1)
break;
long hash = 1;
while (c != 10) {
hash *= PRIMES[c];
c = reader.read();
}
if (hm.get(hash) == null) {
hm.put(hash, 1);
} else {
int value = hm.get(hash);
total += value;
hm.put(hash, value + 1);
}
}
return total;
} catch (Exception e) {
System.out.println(e);
}
return 0;
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == 'n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
public static void main(String[] args) {
Speed dataProcessor = new Speed();
int answer = dataProcessor.processData(args[0]);
System.out.println(answer);
}
}

素数列表应该以3开头,而不是以2开头。乘以2会导致冲突增加:每次都会丢失一位数据。在其中64个字符之后,不管字符串中还有什么其他字符,哈希代码都是0。

至于其余的代码,使用BufferedReader逐行读取文件要容易得多。它增加的开销是最小的。

相关内容

最新更新