В Java, как мне реализовать хеш-функцию, которая принимает массив строк в качестве аргумента и возвращает значение индекса для этой строки?

Я должен создать хеш-таблицу, которая применяет хеш-функцию к имени и фамилии (ключу) и ищет соответствующий индекс. Номер телефона (значение) должен быть возвращен при поиске. Хотя я действительно прошу помощи с моей хэш-функцией, которая ужасно некорректна, если бы кто-то мог переписать метод по-своему, я с радостью это оценил бы. Я просто запутался в том, как создать хеш-функцию, которая возвращает индекс после вычисления строки. Если кто-то захочет прочитать этот код, вы окажете огромную помощь. Благодарю вас.

PS: мой метод хеш-функции называется hashFunction(строковый ключ)

    import java.util.Scanner;
/*
 * The following class implements a telephone directory search using Hash Tables
 */
public class HashTableImplementation{
    public static void main(String[] args){
        HashTable directory = new HashTable();
        System.out.println("\tWelcome to the Telephone Directory");
        System.out.println("The following directory is pre-populated with 20 people");
        directory.setTableSize();
        directory.insert("John", "7777");
        System.out.print(directory.getTableKey());


    }

}

class LinkListNode{
    private LinkListNode link;
    private String data;

/*\
 * Constructor sets top to null value and counter to 0.
 */
public LinkListNode(String data){
    link = null;
    this.data = data;
}

}
/*
 * The following class provides methods for hash table implementation
 */
class HashTable {
    private String key;
    private String phoneNum;
    private final int TABLE_SIZE = 20;  
    private HashTable[] table;
/*
 * Default constructor
 */
public HashTable(){

}
public HashTable(String key, String value) {
    this.key = key;
    this.phoneNum = value;
}
/*
 * Setting table size implements empty hash-table 
 */
public void setTableSize(){     
    table = new HashTable[TABLE_SIZE];
    for(int i = 0; i < TABLE_SIZE; i++){
        table[i] = null;
    }
}
/*
 * Returns phone number of person in directory
 */
public String getTableValue(int key){
    int hash = (key % TABLE_SIZE);
    while((table[hash] != null) && (!table[hash].getKey().equals(key)) ){
        hash = hash++ % TABLE_SIZE; 
    }
    if(table[hash] == null){
        return null;
    }
    else{
        return table[hash].getValue();
    }
}
/*
 * Returns firstName and lastName of person in directory
 */
public String getTableKey(String key){
    int index = hashFunction(key);
    if(table[index] == null){
        return null;
    }
    return table[index].getKey();
}
/*
 * Function to insert a key-value pair into the hash table
 */
public void insert(String key, String value){
    int index = hashFunction(key);
    table[index] = new HashTable(key, value);
}

public int hashFunction(String key) {
int sum = 0;
int nameLength = table.length;
    for(int i = 0; i < nameLength; i++){
        sum += (int)key.charAt(i);
    }
    return sum % TABLE_SIZE;
}
/*
 * Gets firstName and lastName
 */
public String getKey(){
    return key;
}
/*
 * Gets phone number
 */
public String getValue() {
    return phoneNum;
}
/*
 * Returns hash-table size
 */
public int getSize(){
    return TABLE_SIZE;
}
public String toString(){
    String string;
    string = "" + key;
    return string;

}

}

0 ответов

Другие вопросы по тегам