Question

In: Computer Science

// FILE: table1.h // // ABSTRACT BASE CLASS: Table //    1. The number of records...

// FILE: table1.h
//
// ABSTRACT BASE CLASS: Table
//    1. The number of records in the Table is stored in total_records
// 2. The hashcode function returns a location in the table for the
// input key. It calls hash function in functional library.
// 3. insert and print are two virtual functions to be overridden
// insert: Add a new record into the Table;
//           If key is already in the table, do nothing
// print: print table contents
//
// DERIVED CLASS: ChainTable
//    The actual records are stored in a chained hash table.
//       datatable[i] stores a list of strings
//
// DERIVED CLASS: QuadTable
//    The actual records are stored in an array.
// datatable[i] stores one string
//

#ifndef TABLE_H
#define TABLE_H

#include <string>       // Provide string
#include <functional> // Provide hash
#include <list>        // Provide list
using namespace std;

class Table
{
public:
   // MEMBER CONSTANT
   static const unsigned int TABLE_SIZE = 13;

   Table() { total_records = 0; }
   virtual ~Table() { }

   unsigned int get_total() { return total_records; }

   virtual void insert(string key) =0;
   virtual void print() =0;
  
protected:
   unsigned int total_records;

   // HELPER FUNCTION
   unsigned int hashcode(string key) const
   {
       hash<string> thishash;
       return thishash(key) % TABLE_SIZE;
   }
};

class ChainTable : public Table
{
public:
   ChainTable() {}

   virtual void insert(string key);
   virtual void print();
  
private:
   list<string> datatable[TABLE_SIZE];
};

class QuadTable : public Table
{
public:
   QuadTable() {}
  
   virtual void insert(string key);
   virtual void print();
   bool full() { return total_records == TABLE_SIZE; }
  
private:
   string datatable[TABLE_SIZE];
};

#endif

//------END TABLE1.H-------------------

//------------------BEGIN TABLE1.CPP---------------------

// FILE: table1.cpp

// CLASS IMPLEMENTED: ChainTable and QuadTable (see table1.h for documentation)

#include <iostream>

#include "table1.h"

void ChainTable::insert(string key)

{

    //-----------------------------------------------

    // TO-DO: insert key into the chained hash table

    // ------

    // 1. use hashcode function to calculate bucket index i

    unsigned int index_i = hashcode(key);

    //   2. check if key is already in the linkedlist at datatable[i];

    //   - if yes, do nothing

/* if (!datatable[index_i].empty())

        return;*/ incorrect! -3pts: if the linkedlist at the table entry is not empty, should first see if the key is in the list or not; then if not, insert into the list

    // - if no, insert key into the list, increment total_records

    else

    {

//datatable[index_i].push_back(key); Incorrect! use the linkedlist! Reveiw the table1.h code --> list<string> datatable[TABLE_SIZE]

        total_records++;

    }

}


// print table contents visually

void ChainTable::print()

{

    cout << "ChainTable content: \n";

    if (total_records == 0)

    {

        cout << "\t Empty!\n";

        return;

    }

    for (unsigned int i = 0; i < TABLE_SIZE; i++)

    {

        if (datatable[i].empty())

            continue;

        cout << "\t Entry " << i << ": ";

        for (list<string>::iterator it = datatable[i].begin(); it != datatable[i].end(); it++)

        {

            cout << (*it) << " -> ";

        }

        cout << "NULL\n";

    }

}

//////////////////////////////////////////////////

void QuadTable::insert(string key)

{

    //--------------------------------------------------------------

    // TO-DO: insert key into the hash table using quadratic probing

    // ------

    // 1. if hash table is full, do nothing and return

// ALMOST! -2 pts: lines 70-71: if no collision, should return from the function directly after incrementing total_records.

    if (get_total() == TABLE_SIZE)

    {

        return;

    }

    // 2. use hashcode function to calculate array index i

    unsigned int index = hashcode(key);

    // 3. check if datatable[i] is empty

    if (datatable[index].empty())

        // - if yes, insert key at datatable[i]

        datatable[index] = key;

    // - if no, use quadratic probing with probe function c(i)=i^2,

    // until an empty location is found, insert key at that location

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

    {

        int t = (index + i * i) % TABLE_SIZE;

        if (!datatable[t].empty())

        {

            datatable[t] = key;

            break;

        }

    }

    // 4. increment total_records

    total_records++;

    return;

}

// print table contents visually

void QuadTable::print()

{

    cout << "QuadTable content: \n";

    if (total_records == 0)

    {

        cout << "\t Empty!\n";

        return;

    }

    for (unsigned int i = 0; i < TABLE_SIZE; i++)

    {

        if (datatable[i].empty())

            continue;

        cout << "\t Entry " << i << ": ";

        cout << datatable[i] << endl;

    }

}

I need help fixing the errors in the ChainTable::insert, and QuadTable::insert functions. My implementations are above, but my professor has stated the errors in comments.

for the ChainTable::insert, if the linkedlist at the table entry is not empty, I should first check if the key is in the list or not; then if not, insert into the list using the linkedlist method defined in the private section of the ChainTable class in the table.h file i.e list<string> datatable[TABLE_SIZE]; I cannot figure it out.

for the QuadTable:insert, if no collision, then I should return from the function directly after incrementing total_records. I thought that was already coded properly, but i guess not.

I was also told that  For both tables, a duplicate key should not be inserted.

PLEASE HELP!

Solutions

Expert Solution

Hi, Please find the new code highlighted. Please follow

#include <iostream>
#include "table1.h"

void ChainTable::insert(string key)
{
  
// use hashcode function to calculate bucket index i
unsigned int index_i = hashcode(key);
  
  
// Checks if the List is not empty , then checks for each element in the list and returns if match is found else adds the element in the back.
   if (!datatable[index_i].empty())
   {
       list <string> :: iterator it;
           for(it = datatable.begin(); it != datatable.end(); ++it) {
               if(*it.compare(key)==0)
                   return;
           }
           datatable.push_back(key);
          
   }
  
// If the list is empty at the calculated address then, checks for the emptiness of the list, if size is full return , else adds the element at the given size
  
else  
{
      
       //First we need to declare a list that has to be inserted into the datatable.Push the value in this list and then put value list into datatable[index_i]
      
       list<string> value;
       value.push_back(key);
       datatable[index_i].splice(datatable[index_i].begin(),value);
total_records++;
       }
}


// print table contents visually
void ChainTable::print()
{
cout << "ChainTable content: \n";
if (total_records == 0)
{
cout << "\t Empty!\n";
return;
}
for (unsigned int i = 0; i < TABLE_SIZE; i++)
{
if (datatable[i].empty())
continue;
cout << "\t Entry " << i << ": ";
for (list<string>::iterator it = datatable[i].begin(); it != datatable[i].end(); it++)
{
cout << (*it) << " -> ";
}
cout << "NULL\n";
}
}

//////////////////////////////////////////////////
void QuadTable::insert(string key)
{
//--------------------------------------------------------------
// TO-DO: insert key into the hash table using quadratic probing
// ------
// 1. if hash table is full, do nothing and return

if (get_total() == TABLE_SIZE)
return;
  
// Use hashcode function to calculate array index i
unsigned int index = hashcode(key);
  
// Check if datatable[i] is empty, if yes, insert key at datatable[i]
if (datatable[index].empty()){
datatable[index] = key;
       total_records++;
       return;
   }
  
// - if no, use quadratic probing with probe function c(i)=i^2,
// until an empty location is found, insert key at that location
for (int i = 0; i < TABLE_SIZE; i++)
{
int t = (index + i * i) % TABLE_SIZE;
if (!datatable[t].empty())
{
datatable[t] = key;
break;
}
}
}

// print table contents visually
void QuadTable::print()
{
cout << "QuadTable content: \n";
if (total_records == 0)
{
cout << "\t Empty!\n";
return;
}
for (unsigned int i = 0; i < TABLE_SIZE; i++)
{
if (datatable[i].empty())
continue;
cout << "\t Entry " << i << ": ";
cout << datatable[i] << endl;
}
}


Related Solutions

C++ Programming 1) What is the feature that makes a base class an abstract class? 2)...
C++ Programming 1) What is the feature that makes a base class an abstract class? 2) When designing a class hierarchy involving classes A and B, what are the two questions that must be asked to determine whether class B should be derived from class A?
// Base class for game configuration public abstract class DataSource {     private Graph map;    ...
// Base class for game configuration public abstract class DataSource {     private Graph map;     private HashMap <String,Room> rooms;     private ArrayList <Entity> entities;     private Player player;     protected HashMap < String, List<String[]> > tables;     // constructor     public DataSource() {     }         // Connect to the data source. Override if source is a database     public void connect() {     };         // Load the configuration tables required to build the game world...
This class should include .cpp file, .h file and driver.cpp (using the language c++)! Overview of...
This class should include .cpp file, .h file and driver.cpp (using the language c++)! Overview of complex Class The complex class presents the complex number X+Yi, where X and Y are real numbers and i^2 is -1. Typically, X is called a real part and Y is an imaginary part of the complex number. For instance, complex(4.0, 3.0) means 4.0+3.0i. The complex class you will design should have the following features. Constructor Only one constructor with default value for Real...
// File name: Person.h // Person class declaration. Person is the base class. #pragma once #include...
// File name: Person.h // Person class declaration. Person is the base class. #pragma once #include <iostream> using namespace std; class Person { private:         string fName;         string lName;         int birthYear;         int birthMonth;         int birthDay; public:         Person();         void setName(string, string);         void setBirthDate(int, int, int);         string getFullName();         string getBirthDate(); }; // File name: Person.cpp // Person class definition. Person is the base class. #include "Person.h" Person::Person() { fName = ""; lName =...
What are the “guard statements” that we put in the .h file of a class definition?...
What are the “guard statements” that we put in the .h file of a class definition? Also tell what each of them do. ______________________________________________________________________________________________ What keywords are used to create, and release dynamic memory? ________________________________________________________________________________________ What is being made constant in the following member function of a Monkey class? Explain what each const is doing. const Zip& frappa( const Foo& thing ) const; _________________________________________________________________________________________ Thank you for the explain these problems.
Write a modularized, menu-driven program to read a file with unknown number of records. Input file...
Write a modularized, menu-driven program to read a file with unknown number of records. Input file has unknown number of records of inventory items, but no more than 100; one record per line in the following order: item ID, item name (one word), quantity on hand , and a price All fields in the input file are separated by a tab (‘\t’) or a blank ( up to you) No error checking of the data required Create a menu which...
A Java abstract class is a class that can't be instantiated. That means you cannot create new instances of an abstract class. It works as a base for subclasses. You should learn about Java Inheritance before attempting this challenge.
1. Java Abstract Class (2 pts) () • A Java abstract class is a class that can't be instantiated. That means you cannot create new instances of an abstract class. It works as a base for subclasses. You should learn about Java Inheritance before attempting this challenge.• Following is an example of abstract class:abstract class Book{String title;abstract void setTitle(String s);String getTitle(){return title;}}If you try to create an instance of this class like the following line you will get an error:Book...
Abstract Cart class import java.util.ArrayList; import java.util.HashMap; /** * The Abstract Cart class represents a user's...
Abstract Cart class import java.util.ArrayList; import java.util.HashMap; /** * The Abstract Cart class represents a user's cart. Items of Type T can be added * or removed from the cart. A hashmap is used to keep track of the number of items * that have been added to the cart example 2 apples or 4 shirts. * @author Your friendly CS Profs * @param -Type of items that will be placed in the Cart. */ public abstract class AbstractCart {...
Create a Java class file for a Car class. In the File menu select New File......
Create a Java class file for a Car class. In the File menu select New File... Under Categories: make sure that Java is selected. Under File Types: make sure that Java Class is selected. Click Next. For Class Name: type Car. For Package: select csci2011.lab7. Click Finish. A text editor window should pop up with the following source code (except with your actual name): csci1011.lab7; /** * * @author Your Name */ public class Car { } Implement the Car...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT