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
}
} Fix my code as the current output is: 1->21,2->2,4->4,5->5 and I cannot seem to figure out how to do it. I really need it.

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_2

Step: 3

blur-text-image_3

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

Introduction to Wireless and Mobile Systems

Authors: Dharma P. Agrawal, Qing An Zeng

4th edition

1305087135, 978-1305087132, 9781305259621, 1305259629, 9781305537910 , 978-130508713

More Books

Students also viewed these Programming questions