[Java] Please check your code at the link I provide before you submit your code
ID: 3836402 • Letter: #
Question
[Java] Please check your code at the link I provide before you submit your code here. If your code won't pass the tester in the link, I have to give you a down-thumb. Thanks.
Here's the link: http://www.codecheck.it/files/17040703336th1j7tfhqsu83tf1bute4l7u
Write a program HashCodeSearch to search a file to see if you can find two words that have the same hash code. Read the file with a Scanner and use a data structure that maps the hashcode to a set of words with that hashcode. At the end, print out words that have the same hash code on the same line in lexicographical order. (That will be any set with a length greater than 1)
Finally print the number of duplicates divided by the number of words. It will be a really small number. That is the percentage of collisions.
Set the delimiter to use: scan.useDelimiter("[^A-Za-z0-9_]+");
The book to search is at this URL. (http://www.gutenberg.org/ebooks/2600) Download the plain text and save it in your project as "war_and_peace.txt". The book is "War and Peace" - so there will be lots of words. (586,914).
You can just declare that the main method throws FileNotFoundException. No need for a try/catch
Explanation / Answer
The actual output matches the expected output on the link.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.TreeSet;
/**
* Created by ayushi on 9/5/17.
*/
public class HashCodeSearch {
static HashMap<Integer, HashSet<String>> hashMap = new HashMap<>();
public static void main(String args[]) throws FileNotFoundException
{
File file = new File("war_and_peace.txt");
Scanner sc = new Scanner(file);
sc.useDelimiter("[^A-Za-z0-9_]+");
long num_of_words=0;
while(sc.hasNext())
{
String word = sc.next();
num_of_words++;
int hash = word.hashCode();
if(hashMap.containsKey(hash)){
HashSet<String> def = hashMap.get(hash);
def.add(word);
hashMap.put(hash,def);
}
else{
HashSet<String> def = new HashSet<>();
def.add(word);
hashMap.put(hash,def);
}
}
int buckets=0;
for(HashSet<String> val: hashMap.values())
{
if(val.size()>1) {
buckets++;
TreeSet<String> treeSet = new TreeSet<>(val);
System.out.println(treeSet);
}
}
double collission = (double) buckets/num_of_words;
System.out.println(collission);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.