SlideShare a Scribd company logo
1 of 5
Download to read offline
This class will implement a hash table. The hash table will hold data items whose type is tuple.
This class will have following public methods and constructor. HashTable(int size) Finds the
smallest prime integer p whose value is at least size. Creates a hash table of size p where each
cell initially is NULL. It will determine the hash function to be used in the hash table by creating
the object new HashFunction(p). maxLoad () Returns the maximum load of the hash table
averageLoad () Returns the average load of the hash table size () returns the current size of the
hash table. numElements() returns the number of Tuples that are currently stored in the hash
table. loadFactor() return the load factor which is numElements()/size() add (Tuple t) Adds the
tuple t to the hash table; places t in the list pointed by the cell h(t.getKey()) where h is the hash
function that is being used. When the load factors become bigger than 0.7, then it
(approximately) doubles the size of the hash table and rehashes all the elements (tuples) to the
new hash table. The size of the new hash table must be: Smallest prime integer whose value is at
least twice the current size. search (int k) returns an array list of Tuples (in the hash table) whose
key equals k. If no such Tuples exist, returns an empty list. Note that the type of this method
must be ArrayList remove (Tuple t) Removes the Tuple t from the hash table.
Solution
HashTable.java
import java.math.BigInteger;
import java.util.ArrayList;
public class HashTable {
TupleCell[] hashTable; //Table to store Tuple cells
HashFunction hashFunction; //Current hash Function
public HashTable(int size) {
int actualSize = Math.abs(size);
while (!new BigInteger(Integer.toString(actualSize)).isProbablePrime(1))
actualSize++; //Determining next prime number
hashTable = new TupleCell[actualSize]; //Create tuple cells
hashFunction = new HashFunction(actualSize); //Create hash function
}
public int maxLoad() { //Maximum load in hash table
int maxValue = 0;
for (TupleCell tupleCell : hashTable) {
TupleCell node = tupleCell;
int count = 0;
while (node != null) {
count++;
node = node.nextCell;
}
if (count > maxValue) {
maxValue = count;
}
}
return maxValue;
}
public double averageLoad() { //avarage load in hash table
return ((double) numElements()) / size();
}
public int size() { //size of table
return hashTable.length;
}
public int numElements() { // number of elements in table
int count = 0;
for (TupleCell tupleCell : hashTable) {
TupleCell node = tupleCell;
while (node != null) {
count++;
node = node.nextCell;
}
}
return count;
}
public double loadFactor() { //load factor
return ((double) numElements()) / size();
}
public void add(Tuple t) {
TupleCell node = hashTable[hashFunction.hashIndex(t.getKey())];
if (node == null) {
hashTable[hashFunction.hashIndex(t.getKey())] = new TupleCell(t); //If hash table cell is
empty
} else {
while (node.nextCell != null) {
node = node.nextCell;
}
node.nextCell = new TupleCell(t); //adding new tuple to end of corresponding linked list
}
if (loadFactor() > 0.7) { //Rehash
int newSize = 2 * hashTable.length;
while (!new BigInteger(Integer.toString(newSize))
.isProbablePrime(1))
newSize++; //Finding next prime number
TupleCell[] newHashTable = new TupleCell[newSize];
HashFunction newHashFunction = new HashFunction(newSize);
rehash(newHashTable, newHashFunction); //Rehash based on new hashtable and new
hash function
hashTable = newHashTable;
hashFunction = newHashFunction;
}
}
private void rehash(TupleCell[] newHashTable, HashFunction newHashFunction) { //Rehash
funciton
for (TupleCell tupleCell : hashTable) { //iterating through each cell
TupleCell node = tupleCell;
while (node != null) { //iterating through each node in linked list
TupleCell reNode = newHashTable[newHashFunction
.hashIndex(node.t.getKey())];
if (reNode == null) {
newHashTable[newHashFunction.hashIndex(node.t.getKey())] = node; //Adding to
new hash table
} else {
while (reNode.nextCell != null) {
reNode = reNode.nextCell;
}
reNode.nextCell = node;
}
TupleCell temp = node;
node = node.nextCell;
temp.nextCell = null; //reseting next cell reference
}
}
}
public ArrayList search(int key) {
ArrayList returnList = new ArrayList();
TupleCell node = hashTable[hashFunction.hashIndex(key)]; //Getting corresponding linked
list
while (node != null) {
if (node.t.getKey() == key)
returnList.add(node.t); //match
node = node.nextCell;
}
return returnList;
}
public boolean remove(Tuple t) {
boolean found = false;
TupleCell node = hashTable[hashFunction.hashIndex(t.getKey())];
if (node != null) {
if (node.t.equals(t)) {
hashTable[hashFunction.hashIndex(t.getKey())] = node.nextCell; //if table cell
matches tuple
found = true;
} else {
TupleCell prevNode = node;
while (node != null) {
if (node.t.equals(t)) {
prevNode.nextCell = node.nextCell; //if node in linked list matches tuple
found = true;
break;
}
prevNode = node; //remove node
node = node.nextCell;
}
}
}
return found;
}
static class TupleCell { //Wrapper class for tuple with additional reference to next TupleCell -
for linked list
Tuple t;
TupleCell nextCell;
TupleCell(Tuple t) {
this.t = t;
}
}
}
class HashFunction { //Hash function class
int size;
public HashFunction(int p) {
this.size = p;
}
public int hashIndex(int key) { //key to index method
return Math.abs(key) % size;
}
}
Tuple.java
public class Tuple {
private int key;
public Tuple(int key){
this.key = key;
}
public int getKey() { //used by hash table
return key;
}
public String toString(){
return Integer.toString(key);
}
}

More Related Content

Similar to This class will implement a hash table. The hash table will hold data.pdf

Program 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdfProgram 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdf
ezzi552
 
This will need to be in a header file called LinkedList.hInser.pdf
This will need to be in a header file called LinkedList.hInser.pdfThis will need to be in a header file called LinkedList.hInser.pdf
This will need to be in a header file called LinkedList.hInser.pdf
cleanhome88
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
arorastores
 
Open addressing &amp rehashing,extendable hashing
Open addressing &amp rehashing,extendable hashingOpen addressing &amp rehashing,extendable hashing
Open addressing &amp rehashing,extendable hashing
Haripritha
 
The hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfThe hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdf
vicky309441
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdf
ezonesolutions
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
flashfashioncasualwe
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdf
amirthagiftsmadurai
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructures
martha leon
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
callawaycorb73779
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
In this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdfIn this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdf
EvanpZjSandersony
 
Implement a singly linked list as a functional data structure in Kot.pdf
Implement a singly linked list as a functional data structure in Kot.pdfImplement a singly linked list as a functional data structure in Kot.pdf
Implement a singly linked list as a functional data structure in Kot.pdf
maheshkumar12354
 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdf
fantoosh1
 

Similar to This class will implement a hash table. The hash table will hold data.pdf (20)

Program 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdfProgram 4You are to write an efficient program that will read a di.pdf
Program 4You are to write an efficient program that will read a di.pdf
 
This will need to be in a header file called LinkedList.hInser.pdf
This will need to be in a header file called LinkedList.hInser.pdfThis will need to be in a header file called LinkedList.hInser.pdf
This will need to be in a header file called LinkedList.hInser.pdf
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
 
Open addressing &amp rehashing,extendable hashing
Open addressing &amp rehashing,extendable hashingOpen addressing &amp rehashing,extendable hashing
Open addressing &amp rehashing,extendable hashing
 
Hash table in java
Hash table in javaHash table in java
Hash table in java
 
The hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdfThe hashtable youll be making will use Strings as the keys and Obje.pdf
The hashtable youll be making will use Strings as the keys and Obje.pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdf
 
In C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdfIn C++Write a recursive function to determine whether or not a Lin.pdf
In C++Write a recursive function to determine whether or not a Lin.pdf
 
Complete code in Java The hashtable you'll be making will use String.pdf
Complete code in Java   The hashtable you'll be making will use String.pdfComplete code in Java   The hashtable you'll be making will use String.pdf
Complete code in Java The hashtable you'll be making will use String.pdf
 
(C++ exercise) 1.Implement a circular, doubly linked list with a has.docx
(C++ exercise) 1.Implement a circular, doubly linked list with a has.docx(C++ exercise) 1.Implement a circular, doubly linked list with a has.docx
(C++ exercise) 1.Implement a circular, doubly linked list with a has.docx
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdf
 
Jhtp5 20 Datastructures
Jhtp5 20 DatastructuresJhtp5 20 Datastructures
Jhtp5 20 Datastructures
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
In this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdfIn this homework- you will write a program modify program you wrote in.pdf
In this homework- you will write a program modify program you wrote in.pdf
 
Implement a singly linked list as a functional data structure in Kot.pdf
Implement a singly linked list as a functional data structure in Kot.pdfImplement a singly linked list as a functional data structure in Kot.pdf
Implement a singly linked list as a functional data structure in Kot.pdf
 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdf
 

More from kisgstin23

Describe the E-C and the players involved in the electrical and mech.pdf
Describe the E-C and the players involved in the electrical and mech.pdfDescribe the E-C and the players involved in the electrical and mech.pdf
Describe the E-C and the players involved in the electrical and mech.pdf
kisgstin23
 
Harden, Harden, & Harden is a venerable Wall Street stock brokerage .pdf
Harden, Harden, & Harden is a venerable Wall Street stock brokerage .pdfHarden, Harden, & Harden is a venerable Wall Street stock brokerage .pdf
Harden, Harden, & Harden is a venerable Wall Street stock brokerage .pdf
kisgstin23
 
Every time we have to make a choice we are faced with an opportunity.pdf
Every time we have to make a choice we are faced with an opportunity.pdfEvery time we have to make a choice we are faced with an opportunity.pdf
Every time we have to make a choice we are faced with an opportunity.pdf
kisgstin23
 
Canadian copyrights on music expire 50 years after the death of t.pdf
Canadian copyrights on music expire 50 years after the death of t.pdfCanadian copyrights on music expire 50 years after the death of t.pdf
Canadian copyrights on music expire 50 years after the death of t.pdf
kisgstin23
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdfA linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdf
kisgstin23
 
3. Implement the UnsortedList class to store a list of numbers that .pdf
3. Implement the UnsortedList class to store a list of numbers that .pdf3. Implement the UnsortedList class to store a list of numbers that .pdf
3. Implement the UnsortedList class to store a list of numbers that .pdf
kisgstin23
 
What professions were represented on the teamWhat role did each m.pdf
What professions were represented on the teamWhat role did each m.pdfWhat professions were represented on the teamWhat role did each m.pdf
What professions were represented on the teamWhat role did each m.pdf
kisgstin23
 

More from kisgstin23 (20)

John Smith wrote fraudulent checks and made false statements when ap.pdf
John Smith wrote fraudulent checks and made false statements when ap.pdfJohn Smith wrote fraudulent checks and made false statements when ap.pdf
John Smith wrote fraudulent checks and made false statements when ap.pdf
 
Describe the E-C and the players involved in the electrical and mech.pdf
Describe the E-C and the players involved in the electrical and mech.pdfDescribe the E-C and the players involved in the electrical and mech.pdf
Describe the E-C and the players involved in the electrical and mech.pdf
 
In a large population, 59 of the people have been vaccinated. If 4 .pdf
In a large population, 59  of the people have been vaccinated. If 4 .pdfIn a large population, 59  of the people have been vaccinated. If 4 .pdf
In a large population, 59 of the people have been vaccinated. If 4 .pdf
 
Harden, Harden, & Harden is a venerable Wall Street stock brokerage .pdf
Harden, Harden, & Harden is a venerable Wall Street stock brokerage .pdfHarden, Harden, & Harden is a venerable Wall Street stock brokerage .pdf
Harden, Harden, & Harden is a venerable Wall Street stock brokerage .pdf
 
Every time we have to make a choice we are faced with an opportunity.pdf
Every time we have to make a choice we are faced with an opportunity.pdfEvery time we have to make a choice we are faced with an opportunity.pdf
Every time we have to make a choice we are faced with an opportunity.pdf
 
Complete a Punnett square to show the genotypes and phenotypes expec.pdf
Complete a Punnett square to show the genotypes and phenotypes expec.pdfComplete a Punnett square to show the genotypes and phenotypes expec.pdf
Complete a Punnett square to show the genotypes and phenotypes expec.pdf
 
Did both the North and South initially go to war in 1861 over the is.pdf
Did both the North and South initially go to war in 1861 over the is.pdfDid both the North and South initially go to war in 1861 over the is.pdf
Did both the North and South initially go to war in 1861 over the is.pdf
 
Can really use some help with the following UNIXLINUX commands and .pdf
Can really use some help with the following UNIXLINUX commands and .pdfCan really use some help with the following UNIXLINUX commands and .pdf
Can really use some help with the following UNIXLINUX commands and .pdf
 
Canadian copyrights on music expire 50 years after the death of t.pdf
Canadian copyrights on music expire 50 years after the death of t.pdfCanadian copyrights on music expire 50 years after the death of t.pdf
Canadian copyrights on music expire 50 years after the death of t.pdf
 
Below are common errors. State what was done incorrectly and correct.pdf
Below are common errors. State what was done incorrectly and correct.pdfBelow are common errors. State what was done incorrectly and correct.pdf
Below are common errors. State what was done incorrectly and correct.pdf
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdfA linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdf
 
A. Karl Marx B. Max Weber C. Erik Olin Wright D. Kingsley Davi.pdf
A. Karl Marx  B. Max Weber  C. Erik Olin Wright  D. Kingsley Davi.pdfA. Karl Marx  B. Max Weber  C. Erik Olin Wright  D. Kingsley Davi.pdf
A. Karl Marx B. Max Weber C. Erik Olin Wright D. Kingsley Davi.pdf
 
3. Implement the UnsortedList class to store a list of numbers that .pdf
3. Implement the UnsortedList class to store a list of numbers that .pdf3. Implement the UnsortedList class to store a list of numbers that .pdf
3. Implement the UnsortedList class to store a list of numbers that .pdf
 
4 (Opportunity Cost) You can either spend Spring Break working at hom.pdf
4 (Opportunity Cost) You can either spend Spring Break working at hom.pdf4 (Opportunity Cost) You can either spend Spring Break working at hom.pdf
4 (Opportunity Cost) You can either spend Spring Break working at hom.pdf
 
You isolated an enveloped virus whose virions are able to hemadsorb .pdf
You isolated an enveloped virus whose virions are able to hemadsorb .pdfYou isolated an enveloped virus whose virions are able to hemadsorb .pdf
You isolated an enveloped virus whose virions are able to hemadsorb .pdf
 
What professions were represented on the teamWhat role did each m.pdf
What professions were represented on the teamWhat role did each m.pdfWhat professions were represented on the teamWhat role did each m.pdf
What professions were represented on the teamWhat role did each m.pdf
 
what is the threat and solution for when alice sends a password and .pdf
what is the threat and solution for when alice sends a password and .pdfwhat is the threat and solution for when alice sends a password and .pdf
what is the threat and solution for when alice sends a password and .pdf
 
What is the mechanism of action of Staphylococcus alpha toxinSol.pdf
What is the mechanism of action of Staphylococcus alpha toxinSol.pdfWhat is the mechanism of action of Staphylococcus alpha toxinSol.pdf
What is the mechanism of action of Staphylococcus alpha toxinSol.pdf
 
What is a charismatic leader What problems are charismatic leaders .pdf
What is a charismatic leader What problems are charismatic leaders .pdfWhat is a charismatic leader What problems are charismatic leaders .pdf
What is a charismatic leader What problems are charismatic leaders .pdf
 
What is the difference between sequential file access and random fil.pdf
What is the difference between sequential file access and random fil.pdfWhat is the difference between sequential file access and random fil.pdf
What is the difference between sequential file access and random fil.pdf
 

Recently uploaded

Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
cupulin
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 

Recently uploaded (20)

Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 

This class will implement a hash table. The hash table will hold data.pdf

  • 1. This class will implement a hash table. The hash table will hold data items whose type is tuple. This class will have following public methods and constructor. HashTable(int size) Finds the smallest prime integer p whose value is at least size. Creates a hash table of size p where each cell initially is NULL. It will determine the hash function to be used in the hash table by creating the object new HashFunction(p). maxLoad () Returns the maximum load of the hash table averageLoad () Returns the average load of the hash table size () returns the current size of the hash table. numElements() returns the number of Tuples that are currently stored in the hash table. loadFactor() return the load factor which is numElements()/size() add (Tuple t) Adds the tuple t to the hash table; places t in the list pointed by the cell h(t.getKey()) where h is the hash function that is being used. When the load factors become bigger than 0.7, then it (approximately) doubles the size of the hash table and rehashes all the elements (tuples) to the new hash table. The size of the new hash table must be: Smallest prime integer whose value is at least twice the current size. search (int k) returns an array list of Tuples (in the hash table) whose key equals k. If no such Tuples exist, returns an empty list. Note that the type of this method must be ArrayList remove (Tuple t) Removes the Tuple t from the hash table. Solution HashTable.java import java.math.BigInteger; import java.util.ArrayList; public class HashTable { TupleCell[] hashTable; //Table to store Tuple cells HashFunction hashFunction; //Current hash Function public HashTable(int size) { int actualSize = Math.abs(size); while (!new BigInteger(Integer.toString(actualSize)).isProbablePrime(1)) actualSize++; //Determining next prime number hashTable = new TupleCell[actualSize]; //Create tuple cells hashFunction = new HashFunction(actualSize); //Create hash function } public int maxLoad() { //Maximum load in hash table int maxValue = 0; for (TupleCell tupleCell : hashTable) { TupleCell node = tupleCell; int count = 0;
  • 2. while (node != null) { count++; node = node.nextCell; } if (count > maxValue) { maxValue = count; } } return maxValue; } public double averageLoad() { //avarage load in hash table return ((double) numElements()) / size(); } public int size() { //size of table return hashTable.length; } public int numElements() { // number of elements in table int count = 0; for (TupleCell tupleCell : hashTable) { TupleCell node = tupleCell; while (node != null) { count++; node = node.nextCell; } } return count; } public double loadFactor() { //load factor return ((double) numElements()) / size(); } public void add(Tuple t) { TupleCell node = hashTable[hashFunction.hashIndex(t.getKey())]; if (node == null) { hashTable[hashFunction.hashIndex(t.getKey())] = new TupleCell(t); //If hash table cell is empty } else {
  • 3. while (node.nextCell != null) { node = node.nextCell; } node.nextCell = new TupleCell(t); //adding new tuple to end of corresponding linked list } if (loadFactor() > 0.7) { //Rehash int newSize = 2 * hashTable.length; while (!new BigInteger(Integer.toString(newSize)) .isProbablePrime(1)) newSize++; //Finding next prime number TupleCell[] newHashTable = new TupleCell[newSize]; HashFunction newHashFunction = new HashFunction(newSize); rehash(newHashTable, newHashFunction); //Rehash based on new hashtable and new hash function hashTable = newHashTable; hashFunction = newHashFunction; } } private void rehash(TupleCell[] newHashTable, HashFunction newHashFunction) { //Rehash funciton for (TupleCell tupleCell : hashTable) { //iterating through each cell TupleCell node = tupleCell; while (node != null) { //iterating through each node in linked list TupleCell reNode = newHashTable[newHashFunction .hashIndex(node.t.getKey())]; if (reNode == null) { newHashTable[newHashFunction.hashIndex(node.t.getKey())] = node; //Adding to new hash table } else { while (reNode.nextCell != null) { reNode = reNode.nextCell; } reNode.nextCell = node; } TupleCell temp = node; node = node.nextCell;
  • 4. temp.nextCell = null; //reseting next cell reference } } } public ArrayList search(int key) { ArrayList returnList = new ArrayList(); TupleCell node = hashTable[hashFunction.hashIndex(key)]; //Getting corresponding linked list while (node != null) { if (node.t.getKey() == key) returnList.add(node.t); //match node = node.nextCell; } return returnList; } public boolean remove(Tuple t) { boolean found = false; TupleCell node = hashTable[hashFunction.hashIndex(t.getKey())]; if (node != null) { if (node.t.equals(t)) { hashTable[hashFunction.hashIndex(t.getKey())] = node.nextCell; //if table cell matches tuple found = true; } else { TupleCell prevNode = node; while (node != null) { if (node.t.equals(t)) { prevNode.nextCell = node.nextCell; //if node in linked list matches tuple found = true; break; } prevNode = node; //remove node node = node.nextCell; } } }
  • 5. return found; } static class TupleCell { //Wrapper class for tuple with additional reference to next TupleCell - for linked list Tuple t; TupleCell nextCell; TupleCell(Tuple t) { this.t = t; } } } class HashFunction { //Hash function class int size; public HashFunction(int p) { this.size = p; } public int hashIndex(int key) { //key to index method return Math.abs(key) % size; } } Tuple.java public class Tuple { private int key; public Tuple(int key){ this.key = key; } public int getKey() { //used by hash table return key; } public String toString(){ return Integer.toString(key); } }