Question

In: Computer Science

INSERT STRING INTO SEPARATE CHAIN HASHTABLE & ITERATE THROUGH HASHTABLE: JAVA _________________________________________________________________________________________________________________ import java.util.*; public class...

INSERT STRING INTO SEPARATE CHAIN HASHTABLE & ITERATE THROUGH HASHTABLE: JAVA

_________________________________________________________________________________________________________________

import java.util.*;

public class HashTable implements IHash {
// Method of hashing
private HashFunction hasher;
// Hash table : an ArrayList of "buckets", which store the actual strings
private ArrayList<List<String>> hashTable;
/**
* Number of Elements
*/
private int numberOfElements;
private int numberOfBuckets;

/**
* Initializes a new instance of HashTable.
* <p>
* Initialize the instance variables. <br>
* Note: when initializing the hashTable, make sure to allocate each entry in the HashTable
* to a new a HashBucket or null, your choice.
* @param numberOfBuckets the size of the hashTable
* @param hasher the type of hashing function
*/
public HashTable(int numberOfBuckets, HashFunction hasher) {
   this.hasher = hasher;
   this.numberOfBuckets = numberOfBuckets;
   this.hashTable = new ArrayList<>();
   for (int i = 0; i < numberOfBuckets; i++) {
       hashTable.add(null);
   }
   this.numberOfElements = 0;
}

public boolean insert(String key) { // THIS METHOD NEEDS HELP
   int bucketToPlaceIn = hasher.hash(key) % numberOfBuckets;
   List<String> bucketContents = hashTable.get(bucketToPlaceIn);
   // if bucketToPlaceIn is null
       // initialize bucketContents
       // set hashTable at bucketToPlaceIn equal to bucketContents
   // if bucketContents doesn't contain the key
       // add it
       // return true
   return false;
}

public boolean remove(String key) {
   for (int i = 0; i < hashTable.size(); i++) {
       for (int j = 0; j < hashTable.get(i).size(); j++) {
           if (hashTable.get(i).get(j) == key) {
               hashTable.get(i).remove(j);
               return true;
           }
       }
   }
return false;
}

public String search(String key) {
   for (int i = 0; i < hashTable.size(); i++) {
       for (int j = 0; j < hashTable.get(i).size(); j++) {
           if (hashTable.get(i).get(j) == key) {
               return key;
           }
       }
   }
   return null;
}

public int size() {
   int returnSize = 0;
   for (int i = 0; i < hashTable.size(); i++) {
       returnSize += hashTable.get(i).size();
   }
   return returnSize;
}

public int size(int index) {
   int returnSize = hashTable.get(index).size();
return returnSize;
}

// Return iterator for the entire hashTable,
// must iterate all hashBuckets that are not empty
public class HashIterator implements Iterator<String> {
// The current index into the hashTable
private int currentIndex;
// The current iterator for that hashBucket
private Iterator<String> currentIterator = null;

HashIterator() { // THIS METHOD NEEDS HELP
// YOUR CODE HERE
}


public String next() { // THIS METHOD NEEDS HELP
// YOUR CODE HERE
return null;
}

public boolean hasNext() { // THIS METHOD NEEDS HELP
// YOUR CODE HERE
return false;
}
}

// Return an iterator for the hash table
public Iterator<String> iterator() { // THIS METHOD NEEDS HELP
// YOUR CODE HERE
return null;
}

/**
* Does not use the iterator above. Iterates over one bucket.
*
* @param index the index of bucket to iterate over
* @return an iterator for that bucket
*/
public Iterator<String> iterator(int index) {
List<String> bucket = hashTable.get(index);
return bucket != null ? bucket.iterator() : null;
}

// Prints entire hash table.
// NOTE: This method is used extensively for testing.
public void print() {
Debug.printf("HashTable size: " + size());

for (int index = 0; index < hashTable.size(); index++) {
List<String> list = hashTable.get(index);
if (list != null) {
Debug.printf("HashTable[%d]: %d entries", index, list.size());
for (String word : list) {
Debug.printf("String: %s (hash code %d)", word, hasher.hash(word));
}
}else {
Debug.printf("HashTable[%d]: %d entries", index, 0);
}
}
}
}

FOR REFERENCE

// HashInterface.java - interface for hashing assignment

import java.util.Iterator;

public interface IHash {

/** Add a key to the hash table, if it is not currently in the table
* @param key - the key to add
* @return true on success, false on failure (duplicate)
*/
public abstract boolean insert(String key);

/** Remove a key from the hash table
* @param key - the key to remove
* @return true on success, false on failure (not in table)
*/
public abstract boolean remove(String key);

/** Search for a key in the hash table
* @param key - the key to search for
* @return the key on success, null on failure (not in table)
*/
public abstract String search(String key);

/** Get the number of elements in the hash table
* @return the number of elements in the table
*/
public abstract int size();

/** Get the number of elements in the hash table at the given index
* @param i the index in the hash table (0 to size-1)
* @return the size of the list in the i<sup>th</sup> bucket
*/
public abstract int size(int i);

/** Get an iterator that return the Strings stored in
* the hash table one at a time. The order should be in order of entries in
* the hash table itself and for a given bucket, the order in that list.
* @return an Interator
*/
public abstract Iterator<String> iterator();

/** Get an iterator for the i<sup>th</sup> bucket
* @param i the index in the hash table (0 to size-1)
* @return null if the bucket is empty, otherwise an iterator for the bucket
*/
public abstract Iterator<String> iterator(int i);
  
/** Print the entire hash table.
*/
public abstract void print();
}


@FunctionalInterface
interface HashFunction {
int hash(String key);
}


public class Hasher {

// Hashing algorithms, see specification

/**
* Hashing algorithms, see provided documentation in assignment
* @param hashFunction FIRST, SUM, PRIME, OR JAVA
* @return the corresponding HashFunction
*/
public static HashFunction make(String hashFunction) {
switch (hashFunction) {
case "FIRST":
   return (String key) -> {
       return Math.abs(key.charAt(0));
   };
          
case "SUM":
   return (String key) -> {
   int sumReturn = 0;
       for (int i = 0; i < key.length(); i++) {
       sumReturn += Math.abs(key.charAt(i));
   }
               return sumReturn;
   };

case "PRIME":
   return (String key) -> {
   int sumReturn = 7;
       for (int i = 0; i < key.length(); i++) {
       sumReturn = (31*sumReturn) + Math.abs(key.charAt(i));
   }
               return sumReturn;
   };

case "JAVA":
   return (String key) -> {
       return key.hashCode();
   };

default:
usage();
}
return null;
}


// Usage message
private static void usage() {
System.err.println("Usage: java Hasher <FIRST|SUM|PRIME|JAVA> <word>");
System.exit(1);
}

// Test code for hasher
public static void main(String[] args) {
args = Debug.init(args);
if (args.length != 2)
usage();

HashFunction sh = make(args[0]);
int hashCode = sh != null ? sh.hash(args[1]) : 0;
System.out.printf("'%s' hashes to %d using %s\n", args[1], hashCode, args[0]);
}
}

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Attached only HashTable.java since other files are not modified.

// HashTable.java

import java.util.*;

public class HashTable implements IHash {

      // Method of hashing

      private HashFunction hasher;

      // Hash table : an ArrayList of "buckets", which store the actual strings

      private ArrayList<List<String>> hashTable;

      private int numberOfBuckets;

      /**

      * Initializes a new instance of HashTable.

      * <p>

      * Initialize the instance variables. <br>

      * Note: when initializing the hashTable, make sure to allocate each entry

      * in the HashTable to a new a HashBucket or null, your choice.

      *

      * @param numberOfBuckets

      *            the size of the hashTable

      * @param hasher

      *            the type of hashing function

      */

      public HashTable(int numberOfBuckets, HashFunction hasher) {

            this.hasher = hasher;

            this.numberOfBuckets = numberOfBuckets;

            this.hashTable = new ArrayList<List<String>>();

            for (int i = 0; i < numberOfBuckets; i++) {

                  hashTable.add(null);

            }

      }

      public boolean insert(String key) { // THIS METHOD NEEDS HELP

            int bucketToPlaceIn = hasher.hash(key) % numberOfBuckets;

            // if bucketToPlaceIn is null

            // initialize bucketContents

            if (hashTable.get(bucketToPlaceIn) == null) {

                  hashTable.set(bucketToPlaceIn, new ArrayList<String>());

            }

            // set hashTable at bucketToPlaceIn equal to bucketContents

            List<String> bucketContents = hashTable.get(bucketToPlaceIn);

            // if bucketContents doesn't contain the key

            // add it

            // return true

            if (!bucketContents.contains(key)) {

                  bucketContents.add(key);

                  return true;

            }

            return false; // already exist

      }

      public boolean remove(String key) {

            for (int i = 0; i < hashTable.size(); i++) {

                  for (int j = 0; j < hashTable.get(i).size(); j++) {

                        if (hashTable.get(i).get(j) == key) {

                              hashTable.get(i).remove(j);

                              return true;

                        }

                  }

            }

            return false;

      }

      public String search(String key) {

            for (int i = 0; i < hashTable.size(); i++) {

                  for (int j = 0; j < hashTable.get(i).size(); j++) {

                        if (hashTable.get(i).get(j) == key) {

                              return key;

                        }

                  }

            }

            return null;

      }

      public int size() {

            int returnSize = 0;

            for (int i = 0; i < hashTable.size(); i++) {

                  returnSize += hashTable.get(i).size();

            }

            return returnSize;

      }

      public int size(int index) {

            int returnSize = hashTable.get(index).size();

            return returnSize;

      }

      // Return iterator for the entire hashTable,

      // must iterate all hashBuckets that are not empty

      public class HashIterator implements Iterator<String> {

            // The current index into the hashTable

            private int currentIndex;

            // The current iterator for that hashBucket

            private Iterator<String> currentIterator = null;

            HashIterator() { // THIS METHOD NEEDS HELP

                  currentIndex = 0;

                  // finding the first bucket that is not null,

                  for (int i = 0; i < hashTable.size(); i++) {

                        if (hashTable.get(i) != null) {

                              // found, assigning i to current index

                              currentIndex = i;

                              // getting an iterator for current bucket and assigning to

                              // currentIterator

                              currentIterator = hashTable.get(i).iterator();

                              break; // exiting loop

                        }

                  }

            }

            public String next() {

                  // getting next item

                  String item = currentIterator.next();

                  // if iterator is empty, finding the next bucket that is not null

                  // and assigning index and iterator to currentIndex and

                  // currentIterator respectively

                  if (!currentIterator.hasNext()) {

                        for (int i = currentIndex + 1; i < hashTable.size(); i++) {

                              if (hashTable.get(i) != null) {

                                    // found

                                    currentIndex = i;

                                    currentIterator = hashTable.get(i).iterator();

                                    break;

                              }

                        }

                  }

                  return item;

            }

            public boolean hasNext() {

                  // if currentIterator is not null and currentIterator.hasNext()

                  // method returns true, then there are more element(s) to iterate

                  return currentIterator != null && currentIterator.hasNext();

            }

            @Override

            public void remove() {

            }

      }

      // Return an iterator for the hash table

      public Iterator<String> iterator() { // THIS METHOD NEEDS HELP

            return new HashIterator();

      }

      /**

      * Does not use the iterator above. Iterates over one bucket.

      *

      * @param index

      *            the index of bucket to iterate over

      * @return an iterator for that bucket

      */

      public Iterator<String> iterator(int index) {

            List<String> bucket = hashTable.get(index);

            return bucket != null ? bucket.iterator() : null;

      }

      // Prints entire hash table.

      // NOTE: This method is used extensively for testing.

      public void print() {

            Debug.printf("HashTable size: " + size());

            for (int index = 0; index < hashTable.size(); index++) {

                  List<String> list = hashTable.get(index);

                  if (list != null) {

                        Debug.printf("HashTable[%d]: %d entries", index, list.size());

                        for (String word : list) {

                              Debug.printf("String: %s (hash code %d)", word,

                                          hasher.hash(word));

                        }

                  } else {

                        Debug.printf("HashTable[%d]: %d entries", index, 0);

                  }

            }

      }

}


Related Solutions

// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test...
// problem2.java import java.util.*; public class problem_a { public static void main(String[] args) { // test the smallest method System.out.print("smallest(1, 0, 2) -> "); System.out.println( smallest(1, 0, 2) ); // test the average method System.out.print("average(95, 85, 90) -> "); System.out.println( average(95, 84, 90) ); } // end main /* * smallest(double, double, double) -> double * * method is given 3 numbers, produces the smallest of the three * * examples: * smallest(1, 0, 2) -> 0.0 */ public static...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence;...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence; Message() { sentence=""; } Message(String text) { setSentence(text); } void setSentence(String text) { sentence=text; } String getSentence() { return sentence; } int getVowels() { int count=0; for(int i=0;i<sentence.length();i++) { char ch=sentence.charAt(i); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { count=count+1; } } return count; } int getConsonants() { int count=0; for(int i=0;i<sentence.length();i++)...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
import java.util.*;    public class DataAnalysis{    static Set<String> Data_NaN(Set<String> set){        Set<String> set2 =...
import java.util.*;    public class DataAnalysis{    static Set<String> Data_NaN(Set<String> set){        Set<String> set2 = new HashSet<String>();    for (String temp : set) {        temp = temp.replaceAll(        "[^0-9]", "");                  if(!(set.isEmpty())){            set2.add(temp);        }    }    return set2;               } public static void main(String args[]) { // create empty set Set<String> set = new HashSet<String>(); // {3, 25, 33, 21, 55, 43, 78,...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static...
In java. Please explain. Consider the following program: } import java.util.*; public class Chapter7Ex12 { static Scanner console = new Scanner(System.in); public static void main(String[] args) { double num1; double num2; System.out.print("Enter two integers: "); num1 = console.nextInt(); num2 = console.nextInt(); System.out.println(); if (num1 != 0 && num2 != 0) System.out.printf("%.2f\n", Math.sqrt(Math.abs(num1 + num2 + 0.0))); else if (num1 != 0) System.out.printf("%.2f\n", Math.floor(num1 + 0.0)); else if (num2 != 0) System.out.printf("%.2f\n",Math.ceil(num2 + 0.0)); else System.out.println(0); }} a. What is the...
I need a java flowchart diagram for the following code: import java.util.*; public class Main {...
I need a java flowchart diagram for the following code: import java.util.*; public class Main {    public static void main(String[] args) {    Scanner sc=new Scanner(System.in);           System.out.print("Enter the input size: ");        int n=sc.nextInt();        int arr[]=new int[n];        System.out.print("Enter the sequence: ");        for(int i=0;i<n;i++)        arr[i]=sc.nextInt();        if(isConsecutiveFour(arr))        {        System.out.print("yes the array contain consecutive number:");        for(int i=0;i<n;i++)        System.out.print(arr[i]+" ");   ...
import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list =...
import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list = arrayList; return list; } public static void printList(ArrayList<String> arrayList) { System.out.println("Printing in 4 ways\n"); // 1 System.out.println(arrayList); //2 for(String s:arrayList) System.out.print(s+" "); System.out.println(); //3 System.out.println(Arrays.deepToString(list.toArray())); //4 for(int i=0;i<arrayList.size();i++) System.out.print(arrayList.get(i)+" "); System.out.println(); } public static void filterList(ArrayList<String> arrayList) { System.out.println("Filtered in 2 ways\n"); ArrayList<String> copyArrayList = arrayList; //1 for(int i=0;i<arrayList.size();i++) { if(arrayList.get(i).contains("chuck")) { arrayList.remove(i); i--; } } System.out.println(arrayList); //2 copyArrayList.removeIf(str -> str.contains("chunk")); System.out.println(copyArrayList); }   ...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args)...
Determine the Output: Package questions; import java.util.*; public class Quiz1 {       public static void main(String[] args) {             // TODO Auto-generated method stub             System.out.println("*** 1 ***");             ArrayList<Integer>list1=new ArrayList<Integer>();             for(int i=0;i<30;i++)             {                   list1.add(new Integer(i));             }             System.out.print("[");             for(int i=0;i<list1.size();i++)             {                   System.out.print(list1.get(i)+" ");             }             System.out.println("]");                           System.out.println("*** 2 ***");             ArrayList<Integer>list2=new ArrayList<Integer>();             for(int i=30;i<60;i++)             {                   list2.add(i); //Auto Boxing an Integer not need to use new Integer             }             System.out.println(list2); //toString for an ArrayList --created by the Java Programmers                           System.out.println("*** 3 ***");             ArrayList<Integer>list3=new ArrayList<Integer>();             list3.add(list1.remove(22)); //when...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {...
CONVERT CODE FROM JAVA TO C# PLEASE AND SHOW OUTPUT import java.util.*; public class TestPaperFolds {    public static void main(String[] args)    {        for(int i = 1; i <= 4; i++)               //loop for i = 1 to 4 folds        {            String fold_string = paperFold(i);   //call paperFold to get the String for i folds            System.out.println("For " + i + " folds we get: " + fold_string);        }    }    public static String paperFold(int numOfFolds)  ...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public class Number{ public static void main(String[] args) {    Scanner scan = new Scanner(System.in); System.out.println("Enter 20 integers ranging from -999 to 999 : "); //print statement int[] array = new int[20]; //array of size 20 for(int i=0;i<20;i++){ array[i] = scan.nextInt(); //user input if(array[i]<-999 || array[i]>999){ //check if value is inside the range System.out.println("Please enter a number between -999 to 999"); i--; } } //...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT