CSE220 Lab 4-Hashing
CSE220 Lab 4-Hashing
● All your methods must be written in one single .java or .py or .pynb file.
DO NOT CREATE separate files for each task.
● If you are using JAVA, you must include the main method as well which
should test your other methods and print the outputs according to the tasks.
● If you are using PYTHON, then follow the coding templates shared in this
folder.
NOTE:
b.
__hash_function(self,key) this instance method takes only the string key, calculates the hashed in
(As for an odd length string, add the letter 'N' at the end of it. Thus, ‘Morti’
becomes ‘MortiN’ and the consecutive two letters are Mo, rt, iN)
3. Hashtable with Forward Chaining 2.0
Write the insert() function and hash_function() of the HashTable class which uses an array to
store a key-value pair, where the key is a string representing a fruit, and the value is an int
representing its respective price.
hash_function(key)
Takes a key which is a string, and calculates its length. If length is even, the sum of the ascii
values of the even characters is calculated, otherwise, the sum of the ascii values of odd
characters is calculated.
Finally, it returns the sum modded by length of the array
If we call __hash_function(“apple”):
As len(“apple”) is odd, characters in odd indexes (p, l) are taken:
insert(key, value)
Creates a node that contains a tuple which stores the key-value pair as (key, value). Finds index
by passing key to hash_function(). If there is no collision, the node is placed in the index.
If there is a collision, forward chaining is applied. Here, the chain should be arranged in
descending order, i.e, if the node being inserted has the highest value (price), it will be the
head of the chain. Otherwise, you should iterate the chain and insert it in the appropriate
position.
4. Deletion from hashtable
You are given the hash function, h(key) = (key + 3) % 6 for a hash-table of length 6. In this
hashing, forward chaining is used for resolving conflict and a 6-length array of singly linked lists
is used as the hash-table. In the singly linked list, each node has a next pointer, an Integer key
and a string value, for example: (4 (key) , “Rafi” (value)). The hash-table stores this key-value
pair.
Consider,Node class and hashTable are given to you. You just need to complete the
remove(hashTable, key) function.
class Node:
def __init__(self, key, value, next=None):
self.key, self.value, self.next = key, value, next
remove(hashTable, key=4) returns the changed hashTable where (4, “Rafi”) is removed.
remove(hashTable, key=9) returns the same given hashTable since 9 doesn’t exist in the
table.