Question

In this assignment, you will use a Hashtable to determine the common elements in all the lists. If an element appears more than once in one or more lists, the algorithm should capture the instances the element is present in all the lists.

You are given a code that implements a Hashtable as an array of linked lists. You are also given a main function that will create an array of Lists using the input variable values that you enter. Your task is to find the common elements in all the Lists and print them. Implement your algorithm as an extension of the code in the main function, as indicated in the file.

I suggest an idea (described below) to accomplish the above objective using a Hash table. You could use this idea or any other idea (that would use a Hash table) to determine the common elements in all the Lists. You should not use any additional space (barring a Hash table and a List to store the common elements across all the Lists) that would grow with the size of the Lists and the number of Lists.

A brief description of the suggested idea is as follows:

Create and maintain a List (called CommonElementsList that will store the common elements in all the lists that are scanned until then: this is a property that will be maintained throughout the execution of the algorithm). Setup the hash table (say, 'H') using the contents of the first List in the array of Lists as well as copy the contents of the first List to the CommonElementsList.

Now, go through a loop to scan the elements in the other Lists of the array of Lists.
Before beginning to scan a particular List, empty the contents of the CommonElementsList (you could set the nextNodePtr for the head node to be null to accomplish this).
For a particular List that is scanned

If a value in the List is in the Hash table H, then remove an instance of the value from H as well as insert the value to the CommonElementsList.

After scanning a particular List
Empty the contents of the Hash table H
Fill up the Hash table H using the contents of the CommonElementsList
Print out the contents of the CommonElementsList
// This will correspond to the common elements across all the Lists scanned until then

The contents of the CommonElementsList after scanning all the Lists will be the elements that are present in all the Lists. If a value appears more than once in all the Lists, then the number of instances of the value in the CommonElementsList should correspond to the number of instances the value is present in all the Lists.

Note: As part of your deliverables, you are required to develop a pseudo code for the above idea as well as analyze its time complexity and space complexity (without taking into account the space for the Hash table and the CommonElementsList). If you are using any other idea, you should provide a brief description of the idea along with a pseudo code as well as analyze its time complexity and space complexity (without taking into account the space for the Hash table and the CommonElementsList, if you use one).

A sample screenshot is shown below (note that there are at least three instances of '1' in all the five lists, so there are three instances of '1' in the CommonElementsList; similarly, there are at least two instances of '6' in all the five lists).

Enter the number of lists: 5 Enter the number of elements per list: 25 Enter the maximum value for an element: 10 Enter the s

#include <iostream>

#include <stdlib.h> //srand, rand

#include <time.h>//clock_t, clock, CLOCKS_PER_SEC

using namespace std;

// implementing hash tables as an array of linked lists

class Node{

private:

int data;

Node* nextNodePtr;

public:

Node(){}

void setData(int d){

data = d;

}

int getData(){

return data;

}

void setNextNodePtr(Node* nodePtr){

nextNodePtr = nodePtr;

}

Node* getNextNodePtr(){

return nextNodePtr;

}

};

class List{

private:

Node *headPtr;

public:

List(){

headPtr = new Node();

headPtr->setNextNodePtr(0);

}

Node* getHeadPtr(){

return headPtr;

}

bool isEmpty(){

if (headPtr->getNextNodePtr() == 0)

return true;

return false;

}

void insert(int data){

Node* currentNodePtr = headPtr->getNextNodePtr();

Node* prevNodePtr = headPtr;

while (currentNodePtr != 0){

prevNodePtr = currentNodePtr;

currentNodePtr = currentNodePtr->getNextNodePtr();

}

Node* newNodePtr = new Node();

newNodePtr->setData(data);

newNodePtr->setNextNodePtr(0);

prevNodePtr->setNextNodePtr(newNodePtr);

}

void insertAtIndex(int insertIndex, int data){

Node* currentNodePtr = headPtr->getNextNodePtr();

Node* prevNodePtr = headPtr;

int index = 0;

while (currentNodePtr != 0){

if (index == insertIndex)

break;

prevNodePtr = currentNodePtr;

currentNodePtr = currentNodePtr->getNextNodePtr();

index++;

}

Node* newNodePtr = new Node();

newNodePtr->setData(data);

newNodePtr->setNextNodePtr(currentNodePtr);

prevNodePtr->setNextNodePtr(newNodePtr);

}

int read(int readIndex){

Node* currentNodePtr = headPtr->getNextNodePtr();

Node* prevNodePtr = headPtr;

int index = 0;

while (currentNodePtr != 0){

if (index == readIndex)

return currentNodePtr->getData();

prevNodePtr = currentNodePtr;

currentNodePtr = currentNodePtr->getNextNodePtr();

index++;

}

return -1; // an invalid value indicating

// index is out of range

}

bool deleteElement(int deleteData){

Node* currentNodePtr = headPtr->getNextNodePtr();

Node* prevNodePtr = headPtr;

Node* nextNodePtr = headPtr;

while (currentNodePtr != 0){

if (currentNodePtr->getData() == deleteData){

nextNodePtr = currentNodePtr->getNextNodePtr();

prevNodePtr->setNextNodePtr(nextNodePtr);

return true;

}

prevNodePtr = currentNodePtr;

currentNodePtr = currentNodePtr->getNextNodePtr();

}

return false;

}

int countList(){

Node* currentNodePtr = headPtr->getNextNodePtr();

int numElements = 0;

while (currentNodePtr != 0){

numElements++;

currentNodePtr = currentNodePtr->getNextNodePtr();

}

return numElements;

}

void IterativePrint(){

Node* currentNodePtr = headPtr->getNextNodePtr();

while (currentNodePtr != 0){

cout << currentNodePtr->getData() << " ";

currentNodePtr = currentNodePtr->getNextNodePtr();

}

cout << endl;

}

bool containsElement(int searchData){

Node* currentNodePtr = headPtr->getNextNodePtr();

while (currentNodePtr != 0){

if (currentNodePtr->getData() == searchData)

return true;

currentNodePtr = currentNodePtr->getNextNodePtr();

}

return false;

}

};

class Hashtable{

private:

List* listArray;

int tableSize;

public:

Hashtable(int size){

tableSize = size;

listArray = new List[size];

}

int getTableSize(){

return tableSize;

}

void insert(int data){

int hashIndex = data % tableSize;

listArray[hashIndex].insert(data);

}

void deleteElement(int data){

int hashIndex = data % tableSize;

//while (listArray[hashIndex].deleteElement(data));

listArray[hashIndex].deleteElement(data);

}

bool hasElement(int data){

int hashIndex = data % tableSize;

return listArray[hashIndex].containsElement(data);

}

void printHashTable(){

for (int hashIndex = 0; hashIndex < tableSize; hashIndex++){

cout << "Hash Index: " << hashIndex << " : " ;

listArray[hashIndex].IterativePrint();

}

}

void removeAllElements(){

for (int hashIndex = 0; hashIndex < tableSize; hashIndex++)

listArray[hashIndex].getHeadPtr()->setNextNodePtr(0);

}

};

int main(){

int numLists;

cout << "Enter the number of lists: ";

cin >> numLists;

int numElements;

cout << "Enter the number of elements per list: ";

cin >> numElements;

int maxValue;

cout << "Enter the maximum value for an element: ";

cin >> maxValue;

int hashTableSize;

cout << "Enter the size of the hash table: ";

cin >> hashTableSize;

cout << endl;

Hashtable hashTable(hashTableSize);

srand(time(NULL));

List* listArray = new List[numLists];

for (int listArrayIndex = 0; listArrayIndex < numLists; listArrayIndex++){

cout << "Elements generated in List # " << (listArrayIndex) << endl;

for (int index = 0; index < numElements; index++){

int value = rand() % maxValue;

listArray[listArrayIndex].insert(value);

}

listArray[listArrayIndex].IterativePrint();

}

List CommonElementsList;

for (int index = 0; index < numElements; index++){

int value = listArray[0].read(index);

hashTable.insert(value);

CommonElementsList.insert(value);

}

// Continue with the above code and implement here your algorithm to determine

// the common elements in all the lists

// Include print statements to print the common elements found

// among the lists scanned (the lists are scanned one at a time)

// as shown in the sample screenshot in the assignment description.

cout << "\nCommon elements in all the lists " << endl;

CommonElementsList.IterativePrint();

system("pause");

return 0;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:-

#include <iostream>
#include <stdlib.h> //srand, rand
#include <time.h>//clock_t, clock, CLOCKS_PER_SEC
using namespace std;
class Node
{
   private:
   int data;
   Node* nextNodePtr;
   public:
   Node() {}
   void setData(int d)
   {
       data = d;
   }
   int getData()
   {
       return data;
   }
   void setNextNodePtr(Node* nodePtr)
   {
       nextNodePtr = nodePtr;
   }
   Node* getNextNodePtr()
   {
       return nextNodePtr;
   }
};
class List
{
   private:
   Node *headPtr;
   public:
   List()
   {
       headPtr = new Node();
       headPtr->setNextNodePtr(0);
   }
   Node* getHeadPtr()
   {
       return headPtr;
   }
   bool isEmpty()
   {
       if (headPtr->getNextNodePtr() == 0)
           return true;
       return false;
   }
   void insert(int data)
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       Node* prevNodePtr = headPtr;
       while (currentNodePtr != 0)
       {
           prevNodePtr = currentNodePtr;
           currentNodePtr = currentNodePtr->getNextNodePtr();
       }
       Node* newNodePtr = new Node();
       newNodePtr->setData(data);
       newNodePtr->setNextNodePtr(0);
       prevNodePtr->setNextNodePtr(newNodePtr);
   }
   void insertAtIndex(int insertIndex, int data)
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       Node* prevNodePtr = headPtr;
       int index = 0;
       while (currentNodePtr != 0)
       {
           if (index == insertIndex)
               break;
           prevNodePtr = currentNodePtr;
           currentNodePtr = currentNodePtr->getNextNodePtr();
           index++;
       }
       Node* newNodePtr = new Node();
       newNodePtr->setData(data);
       newNodePtr->setNextNodePtr(currentNodePtr);
       prevNodePtr->setNextNodePtr(newNodePtr);
   }
   int read(int readIndex)
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       Node* prevNodePtr = headPtr;
       int index = 0;
       while (currentNodePtr != 0)
       {
           if (index == readIndex)
               return currentNodePtr->getData();
           prevNodePtr = currentNodePtr;
           currentNodePtr = currentNodePtr->getNextNodePtr();
           index++;
       }
       return -1; // an invalid value indicating
       // index is out of range
   }
   bool deleteElement(int deleteData)
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       Node* prevNodePtr = headPtr;
       Node* nextNodePtr = headPtr;
       while (currentNodePtr != 0)
       {
           if (currentNodePtr->getData() == deleteData)
           {
               nextNodePtr = currentNodePtr->getNextNodePtr();
               prevNodePtr->setNextNodePtr(nextNodePtr);
               return true;
           }
           prevNodePtr = currentNodePtr;
           currentNodePtr = currentNodePtr->getNextNodePtr();
       }
       return false;
   }
   int countList()
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       int numElements = 0;
       while (currentNodePtr != 0)
       {
           numElements++;
           currentNodePtr = currentNodePtr->getNextNodePtr();
       }
       return numElements;
   }
   void IterativePrint()
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       while (currentNodePtr != 0)
       {
           cout << currentNodePtr->getData() << " ";
           currentNodePtr = currentNodePtr->getNextNodePtr();
       }
       cout << endl;
   }
   bool containsElement(int searchData)
   {
       Node* currentNodePtr = headPtr->getNextNodePtr();
       while (currentNodePtr != 0)
       {
           if (currentNodePtr->getData() == searchData)
               return true;
           currentNodePtr = currentNodePtr->getNextNodePtr();
       }
       return false;
   }
   void removeAllElements()
   {
       headPtr->setNextNodePtr(0);
   }
};
class Hashtable
{
   private:
   List* listArray;
   int tableSize;
   public:
   Hashtable(int size)
   {
       tableSize = size;
       listArray = new List[size];
   }
   int getTableSize()
   {
       return tableSize;
   }
   void insert(int data)
   {
       int hashIndex = data % tableSize;
       listArray[hashIndex].insert(data);
   }
   void deleteElement(int data)
   {
       int hashIndex = data % tableSize;
       //while (listArray[hashIndex].deleteElement(data));
       listArray[hashIndex].deleteElement(data);
   }
   bool hasElement(int data)
   {
       int hashIndex = data % tableSize;
       return listArray[hashIndex].containsElement(data);
   }
   void printHashTable()
   {
       for (int hashIndex = 0; hashIndex < tableSize; hashIndex++)
       {
           cout << "Hash Index: " << hashIndex << " : ";
           listArray[hashIndex].IterativePrint();
       }
   }
   void removeAllElements()
   {
       for (int hashIndex = 0; hashIndex < tableSize; hashIndex++)
       listArray[hashIndex].getHeadPtr()->setNextNodePtr(0);
   }
};
int main()
{
   int numLists;
   cout << "Enter the number of lists: ";
   cin >> numLists;
   int numElements;
   cout << "Enter the number of elements per list: ";
   cin >> numElements;
   int maxValue;
   cout << "Enter the maximum value for an element: ";
   cin >> maxValue;
   int hashTableSize;
   cout << "Enter the size of the hash table: ";
   cin >> hashTableSize;
   cout << endl;
   Hashtable hashTable(hashTableSize);
   srand(time(NULL));
   List* listArray = new List[numLists];
   for (int listArrayIndex = 0; listArrayIndex < numLists; listArrayIndex++)
   {
       cout << "Elements generated in List # " << (listArrayIndex) << endl;
       for (int index = 0; index < numElements; index++)
       {
           int value = rand() % maxValue;
           listArray[listArrayIndex].insert(value);
       }
       listArray[listArrayIndex].IterativePrint();
   }
   List CommonElementsList;
   for (int index = 0; index < numElements; index++)
   {
       int value = listArray[0].read(index);
       hashTable.insert(value);
       CommonElementsList.insert(value);
   }
   // Continue with the above code and implement here your algorithm to determine
   // the common elements in all the lists
   // Include print statements to print the common elements found
   // among the lists scanned (the lists are scanned one at a time)
   // as shown in the sample screenshot in the project description.
   for (int i = 1; i < numLists; i++)
   {
       cout << "\nCommon elements from list # 0 to list "<<i<<"\n";
       CommonElementsList.removeAllElements();
       for (int j = 0; j < numElements; j++)
       {
           if (hashTable.hasElement(listArray[i].read(j)) != false)
           {
               hashTable.deleteElement(listArray[i].read(j));
               CommonElementsList.insert(listArray[i].read(j));
           }
       }
       hashTable.removeAllElements();
       int count = CommonElementsList.countList();
       for (int j = 0; j < count; j++)
       {
           hashTable.insert(CommonElementsList.read(j));
       }
       CommonElementsList.IterativePrint();
   }
   cout << "\nCommon elements in all the lists " << endl;
   CommonElementsList.IterativePrint();
   system("pause");
   return 0;
}

Output:-

C:\Users\Siva Kumar\Desktop\1.exe Enter the number of lists: 5 Enter the number of elements per list: 25 Enter the maximum va

Please UPVOTE thank you...!!!

Add a comment
Know the answer?
Add Answer to:
In this assignment, you will use a Hashtable to determine the common elements in all the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PLEASE CODE IN C++ AND MAKE IT COPYABLE! In this project, you will design and implement...

    PLEASE CODE IN C++ AND MAKE IT COPYABLE! In this project, you will design and implement an algorithm to determine the next greater element of an element in an array in Θ(n) time, where 'n' is the number of elements in the array. You could use the Stack ADT for this purpose. The next greater element (NGE) for an element at index i in an array A is the element that occurs at index j (i < j) such that...

  • #include <iostream> #include <string> #include <cstring> using namespace std; class Node{       private:       ...

    #include <iostream> #include <string> #include <cstring> using namespace std; class Node{       private:        int data;        Node* nextNodePtr;           public:        Node(){}               void setData(int d){            data = d;        }               int getData(){            return data;        }               void setNextNodePtr(Node* nodePtr){                nextNodePtr = nodePtr;        }                ...

  • A binary tree is a complete binary tree if all the internal nodes (including the root...

    A binary tree is a complete binary tree if all the internal nodes (including the root node) have exactly two child nodes and all the leaf nodes are at level 'h' corresponding to the height of the tree. Consider the code for the binary tree given to you for this question. Add code in the blank space provided for the member function checkCompleteBinaryTree( ) in the BinaryTree class. This member function should check whether the binary tree input by the...

  • Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function...

    Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function has already been implemented for you. // hash.CPP program to implement hashing with chaining #include<iostream> #include "hash.hpp" using namespace std; node* HashTable::createNode(int key, node* next) { node* nw = new node; nw->key = key; nw->next = next; return nw; } HashTable::HashTable(int bsize) { this->tableSize= bsize; table = new node*[tableSize]; for(int i=0;i<bsize;i++) table[i] = nullptr; } //function to calculate hash function unsigned int HashTable::hashFunction(int key)...

  • Please answer this problem in C++, Thank you! Read and study the sample program: "hashing with chaining using singly...

    Please answer this problem in C++, Thank you! Read and study the sample program: "hashing with chaining using singly linked lists", as well as "hashing with chaining using doubly linked lists". Notice this program is complete except it doesn't include the remove function. Write the remove function and test it with the rest of the program including the given main program. Upload your C++ source file. ---Here is the referenced program: "hashing with chaining using singly linked lists". Below this...

  • C++ assignment about doubly linked list

    You are required to write the following functions using this class: class Doubly_linked_list // Use a class Doubly_linked_list to represent an object {     public:     // constructor initialize the nextPtr     Doubly_linked_list()     {         prevPtr = 0; // point to null at the beginning         nextPtr = 0; // point to null at the beginning     }     // get a number     int GetNum()     {         return number;     }     // set a number     void SetNum(int num)     {         number = num;     }     // get the prev pointer     Doubly_linked_list ...

  • Project Description: In this project, you will combine the work you’ve done in previous assignments to...

    Project Description: In this project, you will combine the work you’ve done in previous assignments to create a separate chaining hash table. Overview of Separate Chaining Hash Tables The purpose of a hash table is to store and retrieve an unordered set of items. A separate chaining hash table is an array of linked lists. The hash function for this project is the modulus operator item%tablesize. This is similar to the simple array hash table from lab 5. However, the...

  • Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...

    Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into hash table we insert at an index calculated by the key modulo the array size, what would happen if we instead did key mod (array_size*2), or key mod (array_size/2)? (Describe both cases). Theory answer Here Change your hashtable from the labs/assignments to be an array of linkedlists – so now insertion is done into a linkedlist at that index. Implement insertion and search. This...

  • Please answer in C++ Derive a class called Queue from the linked list described in Assignment...

    Please answer in C++ Derive a class called Queue from the linked list described in Assignment 2 (list of Dates). This means the Queue class will inherit all the properties (data and functions) of the linked list. But, since a queue allows pushing only at the back and popping at the front of the list, you will need to prevent the addition in the front and removal at the back. To do this, you must derive the Queue class in...

  • Please answer in C++. Derive a class called Stack from the linked list described in Assignment...

    Please answer in C++. Derive a class called Stack from the linked list described in Assignment 2 (list of Dates). This means the Stack class will inherit all the properties (data and functions) of the linked list. But, since a stack only allows pushing and popping at the front of the list only, you will need to prevent the operations at the back. To do this, derive the Stack class in such a way that the base class (LinkedList) functions...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT