[Java] Please test your code in the link I provide before you post your answer.
ID: 3836696 • Letter: #
Question
[Java] Please test your code in the link I provide before you post your answer.
The output should be looked like exact same as the tester.
http://www.codecheck.it/files/17040703336th1j7tfhqsu83tf1bute4l7u
Thank you.
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
Hash code prediction code in java:
import java.util.HashMap;
public class MyHashcodeImpl {
public static void main(String a[]){
HashMap<Price, String> hm = new HashMap<Price, String>();
hm.put(new Price("Banana", 20), "Banana");
hm.put(new Price("Apple", 40), "Apple");
hm.put(new Price("Orange", 30), "Orange");
//creating new object to use as key to get value
Price key = new Price("Banana", 20);
System.out.println("Hashcode of the key: "+key.hashCode());
System.out.println("Value from map: "+hm.get(key));
}
}
class Price{
private String item;
private int price;
public Price(String itm, int pr){
this.item = itm;
this.price = pr;
}
public int hashCode(){
System.out.println("In hashcode");
int hashcode = 0;
hashcode = price*20;
hashcode += item.hashCode();
return hashcode;
}
public boolean equals(Object obj){
System.out.println("In equals");
if (obj instanceof Price) {
Price pp = (Price) obj;
return (pp.item.equals(this.item) && pp.price == this.price);
} else {
return false;
}
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String toString(){
return "item: "+item+" price: "+price;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.