Repository navigation
Replies: 1 comment
|
Hi, You can solve this by creating a custom Hash Table using Separate Chaining. Java's HashMap does not guarantee an exact internal table length, so a custom implementation is useful when you need exactly 1361, 1637, and 2011 buckets. Java Codeimport java.io.*;
import java.util.*;
class Dictionary {
private List<Map.Entry<String, Integer>>[] table;
private int size;
@SuppressWarnings("unchecked")
public Dictionary(int capacity) {
size = capacity;
table = new ArrayList[capacity];
for (int i = 0; i < capacity; i++) {
table[i] = new ArrayList<>();
}
}
// Insert a word and count its frequency
public void insert(String word) {
word = word.toLowerCase();
int index = Math.floorMod(word.hashCode(), size);
for (Map.Entry<String, Integer> entry : table[index]) {
if (entry.getKey().equals(word)) {
entry.setValue(entry.getValue() + 1);
return;
}
}
table[index].add(
new AbstractMap.SimpleEntry<>(word, 1)
);
}
public void displaySize() {
System.out.println("Hash Table Length: " + size);
}
public void displayWord(String word) {
int index = Math.floorMod(word.hashCode(), size);
for (Map.Entry<String, Integer> entry : table[index]) {
if (entry.getKey().equalsIgnoreCase(word)) {
System.out.println(
word + " = " + entry.getValue()
);
return;
}
}
System.out.println(word + " not found");
}
}
public class Main {
public static void main(String[] args) {
Dictionary dict1 = new Dictionary(1361);
Dictionary dict2 = new Dictionary(1637);
Dictionary dict3 = new Dictionary(2011);
try (BufferedReader br =
new BufferedReader(new FileReader("words.txt"))) {
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split("[^a-zA-Z0-9]+");
for (String word : words) {
if (!word.isEmpty()) {
dict1.insert(word);
dict2.insert(word);
dict3.insert(word);
}
}
}
System.out.println("All words inserted successfully!");
dict1.displaySize();
dict2.displaySize();
dict3.displaySize();
dict1.displayWord("java");
dict2.displayWord("java");
dict3.displayWord("java");
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}Example outputThe frequency shown is illustrative; actual output depends on words.txt. Explanation
Make sure Hope this helps! Happy coding! |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Java. How do I create 3 different dictionaries with 3 different hash table lengths(1361,1637,2011). Also read all of the words from the text file into each dictionary separately? How would this look like in code?
All reactions