Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

import java.util.function.Function; public class DoubleHashTable implements OpenAddressTable { private int [ ] table; private int size; private Function h 1 ; private Function h 2

import java.util.function.Function;
public class DoubleHashTable implements OpenAddressTable {
private int[] table;
private int size;
private Function h1;
private Function h2;
public DoubleHashTable(int size, Function h1, Function h2){
if (size <=0){
throw new IllegalArgumentException("Table size must be greater than 0");
}
this.size = size;
this.table = new int[size];
this.h1= h1;
this.h2= h2;
}
@Override
public double loadFactor(){
int count =0;
for (int value : table){
if (value !=0){
count++;
}
}
return (double) count / size;
}
@Override
public void insert(int value){
if (value <0){
throw new IllegalArgumentException("Value must be non-negative");
}
int probe =0;
int index = hash(value, probe);
while (table[index]!=0){
probe++;
index =(index + probe * h2.apply(value))% size;
}
table[index]= value;
}
@Override
public int find(int value){
int index = h1.apply(value);
int step = h2.apply(value);
int probe =0;
while (table[index]!=0 && table[index]!= value && probe < size){
index =(index + step)% size;
probe++;
}
return (probe < size && table[index]== value)? index : -1;
}
@Override
public int hash(int key, int probenumber){
// Double hashing using h1 and h2 functions
int result =(h1.apply(key)+ probenumber * h2.apply(key))% size;
return (result <0)? result + size : result;
}
@Override
public String toString(){
StringBuilder result = new StringBuilder();
for (int i =0; i < size; i++){
if (table[i]!=0){
int index = i; // Use the current index directly
if (result.length()>0){
result.append(",");
}
result.append(index).append("->").append(table[i]);
}
}
return result.toString();
}
public static void main(String[] args){
Function h1= key -> key %10;
Function h2= key -> key %5;
DoubleHashTable t = new DoubleHashTable(10, h1, h2);
t.insert(4);
t.insert(5);
t.insert(21);
t.insert(2);
System.out.println(t.toString());
// Expected output: 0->5,1->2,2->21,4->4
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Professional Android 4 Application Development

Authors: Reto Meier

3rd Edition

1118223853, 9781118223857

More Books

Students also viewed these Programming questions

Question

DeterminetheMLEof and identifywhenitiswell-defined.

Answered: 1 week ago

Question

WRITE A MBA PROJECT FOR #Impact of Blockchain on Capital Markets #

Answered: 1 week ago