Question: So I created a hashtable with hash chaining( but not sure if it's correct ), For each number in numbers.tx t(you can create your own
So I created a hashtable with hash chaining(but not sure if it's correct ), For each number in numbers.txt(you can create your own text file for testing with numbers) put it into the hashtable. I timed how long this takes (CPU time). Once the table is loaded, I want to determine how many collisions occurred, that is the question.
And then Output the build time and the collision report to a text file.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class HashCollisionReport {
public static void main(String[] args) throws IOException {
// Create list from input file
BufferedWriter bw = new BufferedWriter(new FileWriter("Random_Inp.txt"));
List intList = new ArrayList<>();
String fileName = "numbers.txt";
int integerContent = 0;
File file = new File(fileName);
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
integerContent = sc.nextInt();
intList.add(integerContent);
}
sc.close();
}catch(FileNotFoundException fnf){
System.out.println("File not found.");
System.exit(0);
}
catch (Exception e) {
System.out.println(" Program terminated Safely...");
}
//Create Map
Map> intMap = new HashMap<>();
long startTime = System.currentTimeMillis();
for(Integer i : intList){
if (!intMap.containsKey(i.hashCode()%intList.size())){
intMap.put(i.hashCode()%intList.size(), new ArrayList<>());
}
intMap.get(i.hashCode()%intList.size()).add(i);
}
long endTime = System.currentTimeMillis();
String totalTime = (endTime-startTime) + " Milliseconds ";
int totalCollision = 0;
bw = new BufferedWriter(new FileWriter("Collision_Report.txt"));
bw.write("Total CPU Time: " + totalTime);
// Get lsit from each bucket and count nuber of list elements the sum - 1 gives collision of each integer
for(Map.Entry> entry : intMap.entrySet()){
List list = entry.getValue();
int collision = 0;
if(list.size() >= 2){
collision+=list.size()-1;
}
String rep = "Value: " + entry.getKey()+"\t" +" Collison: " + collision + " ";
System.out.println("Value: " + entry.getKey()+"\t" +" Collison: " + collision + " ");
bw.write(rep);
totalCollision += collision;
}
bw.write(" Total Collison: " + totalCollision);
bw.flush();
bw.close();
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
