Question

In: Computer Science

Please fill in the code where it says to implement Methods needed to implement include: insert,...

Please fill in the code where it says to implement

Methods needed to implement include: insert, find, remove, and toIndex

//

// STRINGTABLE.JAVA

// A hash table mapping Strings to their positions in the the pattern sequence

// You get to fill in the methods for this part.

//

public class StringTable {

  

private LinkedList<Record>[] buckets;

private int nBuckets;

//

// number of records currently stored in table --

// must be maintained by all operations

//

public int size;

  

  

//

// Create an empty table with nBuckets buckets

//

@SuppressWarnings("unchecked")

public StringTable(int nBuckets)

{

this.nBuckets = nBuckets;

buckets = new LinkedList[nBuckets];

// TODO - fill in the rest of this method to initialize your table

}

  

  

/**

   * insert - inserts a record to the StringTable

   *

   * @param r

   * @return true if the insertion was successful, or false if a

   * record with the same key is already present in the table.

   */

public boolean insert(Record r)

{

// TODO - implement this method

if() {

  

}

return false;

}

  

  

/**

   * find - finds the record with a key matching the input.

   *

   * @param key

   * @return the record matching this key, or null if it does not exist.

   */

public Record find(String key)

{

// TODO - implement this method

return null;

}

  

  

/**

   * remove - finds a record in the StringTable with the given key

   * and removes the record if it exists.

   *

   * @param key

   */

public void remove(String key)

{

// TODO - implement this method

}

  

/**

   * toIndex - convert a string's hashcode to a table index

   *

   * As part of your hashing computation, you need to convert the

   * hashcode of a key string (computed using the provided function

   * stringToHashCode) to a bucket index in the hash table.

   *

   * You should use a multiplicative hashing strategy to convert

   * hashcodes to indices. If you want to use the fixed-point

   * computation with bit shifts, you may assume that nBuckets is a

   * power of 2 and compute its log at construction time.

   * Otherwise, you can use the floating-point computation.

   */

private int toIndex(int hashcode)

{

// Fill in your own hash function here

return 0;

}

  

  

/**

   * stringToHashCode

   * Converts a String key into an integer that serves as input to

   * hash functions. This mapping is based on the idea of integer

   * multiplicative hashing, where we do multiplies for successive

   * characters of the key (adding in the position to distinguish

   * permutations of the key from each other).

   *

   * @param string to hash

   * @returns hashcode

   */

int stringToHashCode(String key)

{

int A = 1952786893;

int v = A;

for (int j = 0; j < key.length(); j++)

{

char c = key.charAt(j);

v = A * (v + (int) c + j) >> 16;

}

return v;

}

/**

   * Use this function to print out your table for debugging

   * purposes.

   */

public String toString()

{

StringBuilder sb = new StringBuilder();

for(int i = 0; i < nBuckets; i++)

{

sb.append(i+ " ");

if (buckets[i] == null)

{

sb.append("\n");

continue;

}

for (Record r : buckets[i])

{

sb.append(r.key + " ");

}

sb.append("\n");

}

return sb.toString();

}

}

Solutions

Expert Solution

package hash;

import java.util.LinkedList;
import java.util.ListIterator;

//
// STRINGTABLE.JAVA
// A hash table mapping Strings to their positions in the the pattern sequence
// You get to fill in the methods for this part.
//
public class StringTable {
    
    private LinkedList<Record>[] buckets;
    private int nBuckets;

    //
    // number of records currently stored in table --
    // must be maintained by all operations
    //
    public int size;
    
    
    //
    // Create an empty table with nBuckets buckets
    //
    @SuppressWarnings("unchecked")
        public StringTable(int nBuckets)
    {
        this.nBuckets = nBuckets;
        buckets = new LinkedList[nBuckets];
        for (int i = 0; i < nBuckets; i++) {
                buckets[i] = new LinkedList<Record>();
        }
    }  
    /**
     * insert - inserts a record to the StringTable
     *
     * @param r
     * @return true if the insertion was successful, or false if a
     *         record with the same key is already present in the table.
     */
    public boolean insert(Record r) 
    {
        String rkey = r.key;
        int rHashCode = stringToHashCode(rkey);
        int indexBucket = toIndex(rHashCode);
        LinkedList<Record> currentBucket = buckets[indexBucket];
        // Corner case
        if (currentBucket.isEmpty() == true) {
                currentBucket.add(r);
                size = size + 1;
                return true;
        }
        ListIterator<Record> Itr = currentBucket.listIterator();
        while (Itr.hasNext()) {
                Record rInBucket = Itr.next();
                if (rkey.equals(rInBucket.key)) {
                        return false;
                }
        }
        currentBucket.addLast(r);
        size += 1;
        return true;
    }  
    /**
     * find - finds the record with a key matching the input.
     *
     * @param key
     * @return the record matching this key, or null if it does not exist.
     */
    public Record find(String key) 
    {
        int rHashCode1 = stringToHashCode(key);
        int indexBucket1 = toIndex(rHashCode1);
        LinkedList<Record> currentBucket1 = buckets[indexBucket1];
        // Corner case
        if (currentBucket1.isEmpty() == true) {
                return null;
        }
        ListIterator<Record> itr1 = currentBucket1.listIterator();
           while (itr1.hasNext()) {
                   Record rInBucket1 = itr1.next();
                   if (key.equals(rInBucket1.key)) {
                           return rInBucket1;
                   }    
           } 
                   return null;
    } 
    /**
     * remove - finds a record in the StringTable with the given key
     * and removes the record if it exists.
     *
     * @param key
     */
    public void remove(String key) 
    {
        int rHashCode2 = stringToHashCode(key);
        int indexBucket2 = toIndex(rHashCode2);
        LinkedList<Record> currentBucket2 = buckets[indexBucket2];        
        if (currentBucket2.isEmpty() == false) {
                ListIterator<Record> itr2 =currentBucket2.listIterator();
                while (itr2.hasNext()) {
                        Record rInBucket2 = itr2.next();
                        if (key.equals(rInBucket2.key)) {
                                size -= 1;
                                currentBucket2.remove(rInBucket2);
                                break;
                        }
                }       
        }       
    }
    /**
     * toIndex - convert a string's hashcode to a table index
     *
     * As part of your hashing computation, you need to convert the
     * hashcode of a key string (computed using the provided function
     * stringToHashCode) to a bucket index in the hash table.
     *
     * You should use a multiplicative hashing strategy to convert
     * hashcodes to indices.  If you want to use the fixed-point     
     * computation with bit shifts, you may assume that nBuckets is a
     * power of 2 and compute its log at construction time.
     * Otherwise, you can use the floating-point computation.
     */
    private int toIndex(int hashcode)
    {
        //set x=((5^(-2))-1/)2. It is an infinite non-repeating decimal.
        double x=(Math.sqrt(5)-1)/2;
        int index=Math.abs((int)(((hashcode*x)%1.0)*nBuckets));
        return index;
    } 
    /**
     * stringToHashCode
     * Converts a String key into an integer that serves as input to
     * hash functions.  This mapping is based on the idea of integer
     * multiplicative hashing, where we do multiplies for successive
     * characters of the key (adding in the position to distinguish
     * permutations of the key from each other).
     *
     * @param string to hash
     * @returns hashcode
     */
    int stringToHashCode(String key)
    {
        int A = 1952786893;
        
        int v = A;
        for (int j = 0; j < key.length(); j++)
            {
                char c = key.charAt(j);
                v = A * (v + (int) c + j) >> 16;
            }
        
        return v;
    }

    /**
     * Use this function to print out your table for debugging
     * purposes.
     */
    public String toString() 
    {
        StringBuilder sb = new StringBuilder();
        
        for(int i = 0; i < nBuckets; i++) 
            {
                sb.append(i+ "  ");
                if (buckets[i] == null) 
                    {
                        sb.append("\n");
                        continue;
                    }
                for (Record r : buckets[i]) 
                    {
                        sb.append(r.key + "  ");
                    }
                sb.append("\n");
            }
        return sb.toString();
    }
}

Related Solutions

C++ Please Fill in for the functions for the code below. The functions will implement an...
C++ Please Fill in for the functions for the code below. The functions will implement an integer list using dynamic array ONLY (an array that can grow and shrink as needed, uses a pointer an size of array). Additional public helper functions or private members/functions can be used. The List class will be instantiated via a pointer and called similar to the code below: class List { public: // Default Constructor List() {// ... } // Push integer n onto...
C++ Please Fill in for the functions for the code below. The functions will implement an...
C++ Please Fill in for the functions for the code below. The functions will implement an integer stack using deques ONLY. It is possible to use only one deque but using two deques also works. Additional public helper functions or private members/functions can be used. The Stack class will be instantiated via a pointer and called as shown below: Stack *ptr = new Stack(); ptr->push(value); int pop1 = ptr->pop(); int pop2 = ptr->pop(); bool isEmpty = ptr->empty(); class Stack{     public:...
C++ please Fill in for the functions for the code below. The functions will implement an...
C++ please Fill in for the functions for the code below. The functions will implement an integer stack using deques ONLY. It is possible to use only one deque but using two deques also works. Additional public helper functions or private members/functions can be used. The Stack class will be instantiated via a pointer and called as shown below: Stack *ptr = new Stack(); ptr->push(value); int pop1 = ptr->pop(); int pop2 = ptr->pop(); bool isEmpty = ptr->empty(); class Stack{     public:...
Given the StudentIDDriver.java file, fill in the ‘gaps’ in the code (designated by insert code here...
Given the StudentIDDriver.java file, fill in the ‘gaps’ in the code (designated by insert code here that “exercises” (tests) the StudentID class by calling its methods. There are six occurrences of ‘insert code here comments’. Above these are comments that help you understand what your code should accomplish.   Don’t forget to comment your StudentIDDriver.java file (including a prologue section at the top of the file). Create a project in Eclipse for your StudentIdDriver. Add another class for it StudentId Sample...
Please finish this code (Java) 1. Fill in the compare methods for the CompareByPlayoffsAndSalary and CompareByWinsLossesChamps...
Please finish this code (Java) 1. Fill in the compare methods for the CompareByPlayoffsAndSalary and CompareByWinsLossesChamps classes 2. In the CompareByPlayoffsAndSalary the compare method should list: (a) teams that made the playoffs last year before teams that did not. (b) If this is the same then it should list teams with lower salary first. 3. In the CompareByWinsLossesChamps list: (a) teams with more wins first. (b) If the same then list by teams with fewer losses. (c) If this is...
Please implement the 5 questions in source code: #include <stdio.h> #include <stdlib.h> #include <math.h> int main(...
Please implement the 5 questions in source code: #include <stdio.h> #include <stdlib.h> #include <math.h> int main( int argc, char* argv[] ) { // Size of vectors int n = 10000; // Input vectors double *restrict a; double *restrict b; // Output vector double *restrict c; // Size, in bytes, of each vector size_t bytes = n*sizeof(double); /* Q1: Allocate memory for vector a (10 points)*/ /* Q2: Allocate memory for vector b (10 points)*/ /* Q3: Allocate memory for vector...
Start with the provided code for the class linkedListType. Be sure to implement search, insert, and...
Start with the provided code for the class linkedListType. Be sure to implement search, insert, and delete in support of an unordered list (that code is also provided). Now, add a new function called insertLast that adds a new item to the END of the list, instead of to the beginning of the list. Note: the link pointer of the last element of the list is NULL. Test your new function in main. Submit a .zip of your entire project....
IN JAVA. I have the following code (please also implement the Tester to test the methods...
IN JAVA. I have the following code (please also implement the Tester to test the methods ) And I need to add a method called public int remove() that should remove the first integer of the array and return it at the dame time saving the first integer and bring down all other elements. After it should decrease the size of the array, and after return and save the integer. package ourVector; import java.util.Scanner; public class ourVector { private int[]...
USING MATLAB Part 2: Insert coins For this part, you are going implement the code that...
USING MATLAB Part 2: Insert coins For this part, you are going implement the code that asks the user to enter coins until they have entered enough for the NAU power juice. Open the insert_coins.m file. Initialize total to 0. We do this because initially, no coins have been entered. Using a loop, ask the user to enter a coin until the total matches or exceeds 115 cents. The input should be a char or string, so make sure that...
Python - Please include running time of push(), pop(), and top() methods and tester code for...
Python - Please include running time of push(), pop(), and top() methods and tester code for all methods. Design a stack ADT using a single queue as an instance variable, and only constant additional local memory within the method bodies. What is the running time of the push(), pop(), and top() methods for your design? Implement your modified stack ADT in Python, including tester code to test all its methods.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT