Given the following hash function: public int hash(int val, int mod) { return va
ID: 3842407 • Letter: G
Question
Given the following hash function:
public int hash(int val, int mod)
{
return val % mod;
}
And given the following class:
public class Student
{
public String name;
public int age;
public int gradeLevel;
}
And finally given the following hash table array:
Student[] hashTable = new Student[100];
1) Create 5 Student objects that will use the hash function using the age and gradeLevel of the Student to create an index values that will not collide in the hashTable
2) Create 2 more Student objects that will generate a collision with any one of the 5 Student objects in step 1
3) Create the insert function that could handle insert of all 7 Student objects. You can use linear probing or separate chaining to handle the collision and it can be written in pseudocode
Explanation / Answer
HI, Please find my implementtion of all three parts.
Please let me know in case of any issue
public class StudentHashTable {
static class Student
{
public String name;
public int age;
public int gradeLevel;
}
public static int hash(int val, int mod)
{
return val % mod;
}
public static void insert(Student[] hashTable, int hash, Student s){
int n = hashTable.length;
int i = hash;
// linear probing
while(hashTable[i] != null){
i = (i+1)%n;
}
hashTable[i] = s;
}
public static void main(String[] args) {
Student[] hashTable = new Student[100];
//1
Student s1 = new Student();
s1.name = "PK";
s1.age = 35;
s1.gradeLevel = 10;
int hash = hash(35, 10);
hashTable[hash] = s1;
Student s2 = new Student();
s2.name = "MK";
s2.age = 49;
s2.gradeLevel = 8;
hash = hash(49, 8);
hashTable[hash] = s2;
Student s3 = new Student();
s3.name = "DK";
s3.age = 49;
s3.gradeLevel = 7;
hash = hash(49, 7);
hashTable[hash] = s3;
Student s4 = new Student();
s4.name = "VK";
s4.age = 28;
s4.gradeLevel = 5;
hash = hash(28, 5);
hashTable[hash] = s4;
Student s5 = new Student();
s5.name = "LK";
s5.age = 32;
s5.gradeLevel = 6;
hash = hash(32, 6);
hashTable[hash] = s5;
//2)
Student s6 = new Student();
s6.name = "FK";
s6.age = 45;
s6.gradeLevel = 10;
hash = hash(45, 10);
hashTable[hash] = s6;
Student s7 = new Student();
s7.name = "GK";
s7.age = 30;
s7.gradeLevel = 6;
hash = hash(30, 6);
hashTable[hash] = s7;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.