SlideShare a Scribd company logo
Assignment 13/assg-13.cppAssignment 13/assg-13.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Assignment 13 Dictionaries and Hash table
* implementations.
*/
#include<cassert>
#include<iostream>
#include"KeyValuePair.hpp"
#include"Employee.hpp"
#include"HashDictionary.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this pro
gram
* will begin with this main function.
*
* @param argc The command line argument count which is the
number of
* command line arguments provided by user when they starte
d
* the program.
* @param argv The command line arguments, an array of chara
cter
* arrays.
*
* @returns An int value indicating program exit status. Usuall
y 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
cout <<"-----
testing Employee record and KeyValuePair class -----------
"<< endl;
KeyValuePair<int, string> pair(42,"blue");
cout <<"test key: "<< pair.key()<< endl;
assert(pair.key()==42);
cout <<"test value: "<< pair.value()<< endl;
assert(pair.value()=="blue");
int id =3;
Employee e(id,"Derek Harter","1234 Main Street, Commerce T
X",12345.67);
cout << e << endl;
assert(e.getId()==3);
assert(e.getName()=="Derek Harter");
cout << endl;
// -----------------------------------------------------------------------
cout <<"-------------- testing quadratic probing ------------------
-----"<< endl;
constint TABLE_SIZE =7;
HashDictionary<int,Employee> dict(TABLE_SIZE, EMPTY_E
MPLOYEE_ID);
cout <<"Newly created hash dictionary should be empty, size:
"<< dict.size()<< endl;
assert(dict.size()==0);
int probeIndex =0;
//cout << "probe index: " << probeIndex
// << " returned probe value: " << dict.probe(id, probeIndex)
// << endl;
//assert(dict.probe(id, probeIndex) == 2);
probeIndex =1;
//cout << "probe index: " << probeIndex
// << " returned probe value: " << dict.probe(id, probeIndex)
// << endl;
//assert(dict.probe(id, probeIndex) == 5);
probeIndex =5;
//cout << "probe index: " << probeIndex
// << " returned probe value: " << dict.probe(id, probeIndex)
// << endl;
//assert(dict.probe(id, probeIndex) == 37);
cout << endl;
// -----------------------------------------------------------------------
cout <<"-------------- testing mid-square hashing ---------------
-------"<< endl;
// the following asserts will only work for 32 bit ints, leave asse
rts
// commented out if you have 64 bit asserts
cout <<"Assuming 32 bit (4 byte) ints for these tests: "<<sizeo
f(int)<< endl;
assert(sizeof(int)==4);
//id = 3918;
//cout << "hash key: " << id
// << " returned hash value: " << dict.hash(id)
// << endl;
//assert(dict.hash(id) == 1);
//id = 48517;
//cout << "hash key: " << id
// << " returned hash value: " << dict.hash(id)
// << endl;
//assert(dict.hash(id) == 6);
//id = 913478;
//cout << "hash key: " << id
// << " returned hash value: " << dict.hash(id)
// << endl;
//assert(dict.hash(id) == 5);
//id = 8372915;
//cout << "hash key: " << id
// << " returned hash value: " << dict.hash(id)
// << endl;
//assert(dict.hash(id) == 4);
// test that the distribution of the hash values
// over the possible slots/buckets looks relatively
// evenly distributed
int counts[TABLE_SIZE]={0};
//for (id = 0; id < 1000000; id++)
//{
// int hash = dict.hash(id);
// counts[hash]++;
//}
// display results
int sum =0;
for(int slot =0; slot < TABLE_SIZE; slot++)
{
cout <<"counts for slot["<< slot <<"] = "
<< counts[slot]<< endl;
sum = sum + counts[slot];
}
// spot check results
//assert(sum == 1000000);
//assert(counts[0] == 143055);
//assert(counts[6] == 142520);
cout << endl;
// -----------------------------------------------------------------------
cout <<"-------------- testing dictionary insertion ---------------
-----"<< endl;
id =438901234;
//dict.insert(id, Employee(id, "Derek Harter", "123 Main St. Co
mmerce TX", 58.23));
id =192834192;
//dict.insert(id, Employee(id, "Alice White", "384 Bois'darc. Ca
mpbell TX", 45.45));
id =998439281;
//dict.insert(id, Employee(id, "Bob Green", "92 Washington Apt
. 5 Greenville TX", 16.00));
id =362817371;
//dict.insert(id, Employee(id, "Carol Black", "8913 FM 24 Coop
er TX", 28.50));
cout <<"After inserting "<< dict.size()<<" employees:"<< endl
;
cout << dict << endl;
// spot check that hash table entries were correctly performed
//assert(dict.size() == 4);
//assert(dict[3].key() == 192834192);
//assert(dict[3].value().getName() == "Alice White");
//assert(dict[1].key() == 438901234);
//assert(dict[1].value().getName() == "Derek Harter");
cout << endl;
// -----------------------------------------------------------------------
cout <<"-------------- testing dictionary search ------------------
-----"<< endl;
id =438901234;
//e = dict.find(id);
//cout << "Search for id: " << id << endl;
//cout << " Found employee: " << e << endl;
//assert(e.getId() == id);
//assert(e.getName() == "Derek Harter");
id =362817371;
//e = dict.find(id);
//cout << "Search for id: " << id << endl;
//cout << " Found employee: " << e << endl;
//assert(e.getId() == id);
//assert(e.getName() == "Carol Black");
id =239481432;
//e = dict.find(id);
//cout << "Unsuccessful Search for id: " << id << endl;
//cout << " Found employee: " << e << endl;
//assert(e.getId() == EMPTY_EMPLOYEE_ID);
//assert(e.getName() == "");
cout << endl;
// return 0 to indicate successful completion
return0;
}
Assignment 13/assg-13.pdf
Assg 13: Dictionaries and Hashing
COSC 2336 Spring 2019
April 18, 2019
Dates:
Due: Sunday May 05, by Midnight
Objectives
• More practice with using class templates
• Learn about implementing and using key/value pair Dictionary
ab-
straction
• Implement and learn about some basic hashing techniques,
like mid-
square hasing and quadratic probing for closed hashing
schemes.
Description
In this assignment you will be implementing some basic
mechanisms of a
hash table to implement a Dictionary that uses hashing to store
and search
for items in its collection. You have been given many files for
this assign-
ment. I have provided an Employee class in
"Employee.[hpp|cpp]" and a
KeyValuePair class in "KeyValuePair.[hpp|cpp]". You will not
need to make
any changes to these files or classes, they should work as given
for this as-
signment.
You will be adding and implementing some member functions to
the
HashDictionary class. The initial "HashDictionary.[hpp|cpp]"
file contains
a constructor and destructor for a HashDictionary as well as
some other
accessors and operators already implemented that are used for
testing.
You will be implementing a closed hash table mechanism using
quadratic
probing of the slots. You will also implement a version of the
mid-square
1
hashing function described in our textbook (Shaffer section
9.4.3 on closed
hashing mechinsms).
For this assignment you need to perform the following tasks.
1. Your first task is to implement methods to define the probe
sequence
for closed hasing. Add a member function named probe() to the
HashDictionary class. Be aware that the HashDictionary class is
a templatized on <Key, Value> templates, thus when you
implement
the class methods you need to templatize the class methods
correctly.
You can look at the example implementations of size() and the
con-
structors to remind yourself how to do this correctly.
In any case, probe() is a member function that takes two
parameters,
a Key and an integer index value. We are not using secondary
hashing
(as described in our textbook) so the Key value will actually not
be
used in your function. However, keep it as a parameter as the
gen-
eral abstraction/API for the probe function should include it for
cases
where secondary hashing is used. probe() should be a const
class
member function, as calling it does not change the dictionary.
Finally
probe() will return an ineger as its result.
Your probe() funciton should implement a quadratic probing
scheme
as described in our Shaffer textbook section 9.4.3 on pg. 338.
Use
c1 = 1, c2 =2, c3 = 2 as the parameters for your quadratic probe
(the tests of probe() assume your probe sequence is using these
pa-
rameter values for the quadratic function).
2. You second tasks is to implement a hash function for integer
like keys
using the described mid-square hasing function (Shaffer 9.4.1
Example
9.6 pg. 327). We will create a slight variation of this algorithm
for our
hashing dictionary. First of all the hash() member functions
should
take a Key as its only input parameter, and it will then return a
regular
int as its result. Since this is a hash function, the integer value
should
be in the range 0 - tableSize-1, so don’t forget to mod by the
tableSize before returning your hash result.
hash() should work like this. First of all, you should square the
key
value that is passed in. Then, assuming we are working with a
32 bit
int, we want to only keep the middle 16 bits of the square of the
key
to use for our hash. There are many ways to work with and get
the
bits you need, but most likely you will want to use C bitwise
operators
to do this. For example, a simple method to get the middle 16
bits is
2
to first mask out the upper 8 bits using the bitwise & operator
(e.g.
key & 0x00FFFFFF) will mask out the high order 8 bits to 0).
Then
once you have removed the upper most significant 8 bits, you
can left
shift the key by 8 bits, thus dropping out the lower least
significant
8 bits (e.g. key >> 8). Performing a mask of the upper 8 bits and
shifting out the lower 8 bits will result in you only retaining the
middle
16 bits.
If your system is using 64 bit integers rather than 32 bit
integers,
perform the mid-square method but retain the middle 32 bits of
the
result. You can use the sizeof(int) method to determine how
many
bytes are in an int on your system. I will give a bonus point if
you
write your hash() function to correctly work for both 32 and 64
bit
values by testing sizeof(int) and doing the appopriate work to
get
the middle bits. Again after you square the key and get the
middle
bits, make sure you modulo the result to get an actual has index
in the
correct range.
3. The third task is to add the insert() method to your
HashDictionary
so that you can insert new key/value pairs into the dictionary.
insert() should take a constant Key reference and a constant
Value
reference as its input parameters (note that both of these
parameters
should be declared as const, and they should both be reference
pa-
rameters, so use the & to indicate they are passed by reference).
Your
insert() function does not return a result, so it will be a void
func-
tion.
The algorithm for insert is described in Shaffer 9.4.3 on pg.
334. You
need to call and use the probe() and hash() funciton you created
in the first 2 steps to correctly define/implement your closed
hashing
probe sequence. The basica algorithm is that you use hash() to
de-
termine the initial home slot, and probe() gives an offset you
should
add. Basically you have to search the hashTable using the probe
se-
quence until you find an empty slot. Once you find an empty
slot, you
should create a new instance of a KeyValuePair<Key, Value>
object,
that contains the key and value that were provided as input
param-
eters to your insert() function. This KeyValuePair instance
should
then be inserted into the table at the location where you find the
first
empty slot on the probe sequence. Also don’t forget to update
the
valueCount paramemter of the HashDictionary class that keeps
track
of the number of items currently in the dictionary.
3
4. Finally you will also implement the find() method to search
for a
particular key in your dictionary. The find() member function
taks
a single Key parameter as input (it should be a const Key&
reference
parameter). The find() functin will return a Value as a result,
which
will be the Value of the record associated with the given Key if
it was
found in the dictionary, or an empty Value() object if it was not
found.
The find() method uses the same probe sequence as insert()
imple-
mented by your probe() and hash() methods. So you should
again
search along the probe sequence, until you either find the key
you were
given to search for, or else find an empty slot. Then at the end,
if
you found the key in the hashTable you should return the value
that
corresponds to the key that was searched for. If the search
failed and
you found an empty slot on your probe sequence, you should
instead
return an empty Value() object, which is used as an indicator
for a
failed search.
In this assignment you will be given a lot of starting code. As
usual, there is an "assg-13.cpp" file which contains commented
out tests
of the code/functions you are to write. You have been given and
"Em-
ployee.[hpp|cpp]" file containing a simple definition of a (non-
templated)
class/record that holds a few pieces of information about a
theoretical
Employee. We use this class to create a hash dictionary for
testing with
the employee id as the key, and the Employee record as the
associated value
in our Dictionary. You have also been given a template class in
the file
"KeyValuePair.[hpp|cpp]". This contains a templatized
container to holding
a key/value pair of items. You will not need to add any code or
make any
changes in the Employee or KeyValuePair class files.
You have also been given a "HashDictionary.[hpp|cpp]" file
containing
beginning defintions of a HashDictionary class. The member
functions you
need to add for this assignment should be added to these files.
Here is an example of the output you should get if your code is
passing
all of the tests and is able to run the simulation. You may not
get the
exact same statistics for the runSimulation() output, as the
simulation is
generating random numbers, but you should see similar values.
----- testing Employee record and KeyValuePair class -----------
test key: 42
test value: blue
( id: 3, Derek Harter, 1234 Main Street, Commerce TX,
12345.67 )
4
-------------- testing quadratic probing -----------------------
Newly created hash dictionary should be empty, size: 0
probe index: 0 returned probe value: 2
probe index: 1 returned probe value: 5
probe index: 5 returned probe value: 37
-------------- testing mid-square hashing ----------------------
Assuming 32 bit (4 byte) ints for these tests: 4
hash key: 3918 returned hash value: 1
hash key: 48517 returned hash value: 6
hash key: 913478 returned hash value: 5
hash key: 8372915 returned hash value: 4
counts for slot[0] = 143055
counts for slot[1] = 143040
counts for slot[2] = 143362
counts for slot[3] = 142399
counts for slot[4] = 142966
counts for slot[5] = 142658
counts for slot[6] = 142520
-------------- testing dictionary insertion --------------------
After inserting 4 employees:
Slot: 0
Key : 362817371
Value: ( id: 362817371, Carol Black, 8913 FM 24 Cooper TX,
28.50 )
Slot: 1
Key : 438901234
Value: ( id: 438901234, Derek Harter, 123 Main St. Commerce
TX, 58.23 )
Slot: 2
Key : 0
Value: ( id: 0, , , 0.00 )
Slot: 3
Key : 192834192
Value: ( id: 192834192, Alice White, 384 Bois'darc. Campbell
TX, 45.45 )
Slot: 4
5
Key : 998439281
Value: ( id: 998439281, Bob Green, 92 Washington Apt. 5
Greenville TX, 16.00 )
Slot: 5
Key : 0
Value: ( id: 0, , , 0.00 )
Slot: 6
Key : 0
Value: ( id: 0, , , 0.00 )
-------------- testing dictionary search -----------------------
Search for id: 438901234
Found employee: ( id: 438901234, Derek Harter, 123 Main St.
Commerce TX, 58.23 )
Search for id: 362817371
Found employee: ( id: 362817371, Carol Black, 8913 FM 24
Cooper TX, 28.50 )
Unsuccessful Search for id: 239481432
Found employee: ( id: 0, , , 0.00 )
Assignment Submission
A MyLeoOnline submission folder has been created for this
assignment. You
should attach and upload your completed
"HashDictionary.[hpp|cpp]" source
files to the submission folder to complete this assignment. You
do not need
to submit your "assg-13.cpp" file with the tests, nor the
Employee or KeyVal-
uePair files, since you should not have made changes to any of
these (except
to uncomment out the tests in assg-13.cpp). Please only submit
the asked
for source code files, I do not need your build projects,
executables, project
files, etc.
6
Requirements and Grading Rubrics
Program Execution, Output and Functional Requirements
1. Your program must compile, run and produce some sort of
output to
be graded. 0 if not satisfied.
2. (20 pts.) probe() member function implemented. Function is
using
quadratic probing as asked for, with correct values for c1, c2
and c3
parameters. Probe sequence appears correct and passes tests.
3. (20 pts.) hash() member function implemented correctly.
Function
implements the mid-square method as described. Function
correctly
uses only the 16 middle bits if system uses 32 bit integers.
4. (30 pts.) insert() member function implemented and working.
Func-
tion appears to be correctly generating probe sequence using the
probe() and hash() functions. Items are correctly inserted into
ex-
pected location in the hash table.
5. (30 pts.) find() member function implemented and working.
Function
appears to be also correctly using the probe sequence in the
same was
as insert(). Function passes the expected tests.
Program Style
Your programs must conform to the style and formatting
guidelines given
for this class. The following is a list of the guidelines that are
required for
the assignment to be submitted this week.
1. Most importantly, make sure you figure out how to set your
indentation
settings correctly. All programs must use 2 spaces for all
indentation
levels, and all indentation levels must be correctly indented.
Also all
tabs must be removed from files, and only 2 spaces used for
indentation.
2. A function header must be present for member functions you
define.
You must give a short description of the function, and document
all of
the input parameters to the function, as well as the return value
and
data type of the function if it returns a value for the member
functions,
just like for regular functions. However, setter and getter
methods do
not require function headers.
7
3. You should have a document header for your class. The class
header
document should give a description of the class. Also you
should doc-
ument all private member variables that the class manages in
the class
document header.
4. Do not include any statements (such as system("pause") or
inputting
a key from the user to continue) that are meant to keep the
terminal
from going away. Do not include any code that is specific to a
single
operating system, such as the system("pause") which is
Microsoft
Windows specific.
8
Assignment 13/Employee.cppAssignment 13/Employee.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Simple example of an Employee record/class
* we can use to demonstrate HashDictionary key/value pair
* management.
*/
#include<string>
#include<iostream>
#include<iomanip>
#include<sstream>
#include"Employee.hpp"
usingnamespace std;
/** constructor
* Default constructor for our Employee record/class. Construct
an
* empty employee record
*/
Employee::Employee()
{
this->id = EMPTY_EMPLOYEE_ID;
this->name ="";
this->address ="";
this->salary =0.0;
}
/** constructor
* Basic constructor for our Employee record/class.
*/
Employee::Employee(int id, string name, string address,float sal
ary)
{
this->id = id;
this->name = name;
this->address = address;
this->salary = salary;
}
/** id accessor
* Accessor method to get the employee id.
*
* @returns int Returns the integer employee id value.
*/
intEmployee::getId()const
{
return id;
}
/** name accessor
* Accessor method to get the employee name.
*
* @returns string Returns the string containing the full
* employee name for this record.
*/
string Employee::getName()const
{
return name;
}
/** overload operator<<
* Friend function to ouput representation of Employee to an
* output stream.
*
* @param out A reference to an output stream to which we sho
uld
* send the representation of an employee record for display.
* @param employee The reference to the employee record to be
displayed.
*
* @returns ostream& Returns a reference to the original output
* stream, but now the employee information should have been
* inserted into the stream for display.
*/
ostream&operator<<(ostream& out,Employee& employee)
{
//out << "Employee id: " << employee.id << endl
// << " name : " << employee.name << endl
// << " address: " << employee.address << endl
// << " salary : " << fixed << setprecision(2) << employee.s
alary << endl;
out <<"( id: "<< employee.id <<", "
<< employee.name <<", "
<< employee.address <<", "
<< fixed << setprecision(2)<< employee.salary <<" )"<< endl;
return out;
}
Assignment 13/Employee.hpp
/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Simple example of an Employee record/class
* we can use to demonstrate HashDictionary key/value pair
* management.
*/
#include <string>
#include <iostream>
using namespace std;
#ifndef EMPLOYEE_HPP
#define EMPLOYEE_HPP
// This should really be a class constant, however this
// global constant represents a flag that is used to
// indicate empty slots and/or failed search.
const int EMPTY_EMPLOYEE_ID = 0;
/** Employee
* A simple Employee class/record to demonstrate/test
* our hashing dictionary assignment.
* NOTE: we are using 0 as a flag to represent an unused
* slot or an invalid/empty employee. This is used/assumed
* by our dictionary class to determine if a slot is empty
* and/or to give a failure result for a failed search.
*/
class Employee
{
private:
int id;
string name;
string address;
float salary;
public:
Employee();
Employee(int id, string name, string address, float salary);
int getId() const;
string getName() const;
friend ostream& operator<<(ostream& out, Employee&
employee);
};
#endif // EMPLOYEE_HPP
Assignment 13/HashDictionary.cppAssignment
13/HashDictionary.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Template class for definining a dictionary
* that uses a hash table of KeyValuePair items.
* Based on Shaffer hashdict implementation pg. 340
*/
/** constructor
* Standard constructor for the HashDictionary
*
* @param tableSize The size of the hash table that should be
* generated for internal use by this dictionary for hasing.
* @param emptyKey A special flag/value that can be used to d
etect
* invalid/unused keys. We need this so we can indicate which
* slots/buckets in our hash table are currently empty, and also
* this value is used as a return result when an unsuccessful
* search is performed on the dictionary.
*/
template<classKey,classValue>
HashDictionary<Key,Value>::HashDictionary(int tableSize,Key
emptyKey)
{
this->tableSize = tableSize;
this->EMPTYKEY = emptyKey;
valueCount =0;
// allocate an array/table of the indicated initial size
hashTable =newKeyValuePair<Key,Value>[tableSize];
// initialize the hash table so all slots are initially empty
for(int index =0; index < tableSize; index++)
{
hashTable[index].setKey(EMPTYKEY);
}
}
/** destructor
* Standard destructor for the HashDictionary. Be good memor
y managers and
* free up the dynamically allocated array of memory pointed to
by hashTable.
*/
template<classKey,classValue>
HashDictionary<Key,Value>::~HashDictionary()
{
delete[] hashTable;
}
/** size
* Accessor method to get the current size of this dictionary,
* e.g. the count of the number of key/value pairs currently bein
g
* managed in our hash table.
*
* @returns in Returns the current number of items being manag
ed by
* this dictionary and currently in our hashTable.
*/
template<classKey,classValue>
intHashDictionary<Key,Value>::size()const
{
return valueCount;
}
// Place your implementations of the class methods probe(), has
h(),
// insert() and find() here
/** overload indexing operator[]
* Overload indexing operator[] to provide direct access
* to hash table. This is not normally part of the Dictionary
* API/abstraction, but included here for testing.
*
* @param index An integer index. The index should be in the r
ange 0 - tablesize-1.
*
* @returns KeyValuePair<> Returns a KeyValuePair object if t
he index into the
* internal hash table is a valid index. This method throws an
exception if
* the index is not a valid slot of the hash table.
*/
template<classKey,classValue>
KeyValuePair<Key,Value>&HashDictionary<Key,Value>::oper
ator[](int index)
{
if(index <0|| index >= tableSize)
{
cout <<"Error: <HashDictionary::operator[] invalid index: "
<< index <<" table size is currently: "
<< tableSize << endl;
assert(false);
}
return hashTable[index];
}
/** HashDictionary output stream operator
* Friend function for HashDictionary. We normally wouldn't h
ave
* something like this for a Dictionary or HashTable, but for tes
ting
* and learning purposes, we want to be able to display the cont
ents of
* each slot in the hash table of a HashDictionary container.
*
* @param out An output stream reference into which we should
insert
* a representation of the given HashDictionary.
* @param aDict A HashDictionary object that we want to displ
ay/represent
* on an output stream.
*
* @returns ostream& Returns a reference to the original given
output stream,
* but now the values representing the dictionary we were give
n should
* have been sent into the output stream.
*/
template<typename K,typename V>
ostream&operator<<(ostream& out,constHashDictionary<K, V>
& aDict)
{
for(int slot =0; slot < aDict.tableSize; slot++)
{
out <<"Slot: "<< slot << endl;
out <<" Key : "<< aDict.hashTable[slot].key()<< endl;
out <<" Value: "<< aDict.hashTable[slot].value()<< endl;
}
out << endl;
return out;
}
Assignment 13/HashDictionary.hpp
/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Template class for definining a dictionary
* that uses a hash table of KeyValuePair items.
* Based on Shaffer hashdict implementation pg. 340
*/
#include <cassert>
#include <iostream>
#include "KeyValuePair.hpp"
using namespace std;
#ifndef HASHDICTIONARY_HPP
#define HASHDICTIONARY_HPP
/** HashDictionary
* An implementation of a dictionary that uses a hash table to
insert, search
* and delete a set of KeyValuePair items. In the assignment,
we will be
* implementing a closed hashing table with quadratic probing.
The hash function
* will implement a version of the mid-square hasing function
described in
* our Shaffer textbook.
*
* @value hashTable An array of KeyValuePair items, the hash
table this class/container
* is managing.
* @value tableSize The actual size of the hashTable array
* @value valueCount The number of KeyValuePair items that
are currently being
* managed and are contained in the hashTable
* @value EMPTYKEY A special user-supplied key that can be
used to indicate empty
* slots. Since how we determine what is a valid/invalid key
will depend on the
* key type, the user must supply this special flag/value when
setting up the
* hash dictionary.
*/
template <class Key, class Value>
class HashDictionary
{
protected:
KeyValuePair<Key, Value>* hashTable; // the hash table
int tableSize; // the size of the hash table, e.g. symbol M from
textbook
int valueCount; // the count of the number of value items
currently in table
Key EMPTYKEY; // a special user-supplied key that can be
used to indicate empty slots
public:
// constructors and destructors
HashDictionary(int tableSize, Key emptyKey);
~HashDictionary();
// accessor methods
int size() const;
// searching and insertion
// all 4 of the methods you were required to create for this
// assignment should have appropriate class method signatures
// defined here.
// overload operators (mostly for testing)
KeyValuePair<Key, Value>& operator[](int index);
template <typename K, typename V>
friend ostream& operator<<(ostream& out, const
HashDictionary<K, V>& aDict);
};
#include "HashDictionary.cpp"
#endif // HASHDICTIONARY_HPP
Assignment 13/Instructions.png
Assignment 13/KeyValuePair.cppAssignment
13/KeyValuePair.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Template class for definining Key/Value pairs,
* suitable for dictionary and hash table implementations.
* Based on Shaffer KVPair ADT definition, pg. 139 Fig 4.31.
*/
/** constructor
* Default constructor for a KeyValuePair.
*/
template<classKey,classValue>
KeyValuePair<Key,Value>::KeyValuePair()
{
}
/** constructor
* Standard constructor for a KeyValuePair.
*
* @param key The key portion that is to be stored in this pair.
* @param value The value portion that is to be stored in this pa
ir.
*/
template<classKey,classValue>
KeyValuePair<Key,Value>::KeyValuePair(Key key,Valuevalue)
{
this->myKey = key;
this->myValue =value;
}
/** key accessor
* Accessor method to get and return the key for this key/value
pair
*
* @returns Key Returns an object of template type Key, which
is the
* key portion of the pair in this container.
*/
template<classKey,classValue>
KeyKeyValuePair<Key,Value>::key()
{
return myKey;
}
/** key setter
* Accessor method to set the key for this key/value pair
*
* @param key The new value to update the key to for this pair.
*/
template<classKey,classValue>
voidKeyValuePair<Key,Value>::setKey(Key key)
{
this->myKey = key;
}
/** value accessor
* Accessor method to get and return the value for this key/valu
e pair.
*
* @returns Value& Returns a reference to the value object in th
is
* key value pair container.
*/
template<classKey,classValue>
Value&KeyValuePair<Key,Value>::value()
{
return myValue;
}
Assignment 13/KeyValuePair.hpp
/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Template class for definining Key/Value pairs,
* suitable for dictionary and hash table implementations.
* Based on Shaffer KVPair ADT definition, pg. 139 Fig 4.31.
*/
#ifndef KEYVALUEPAIR_HPP
#define KEYVALUEPAIR_HPP
/** KeyValue Pair
* Definition of basic key/value pair container. This container
of course
* associates a value (usually a record like a class or struct),
with
* a key (can be anything).
*
* We do not use the comparator Strategy pattern as discussed
in
* Shaffer pg. 144 here. We assume that the Key type has
suitably
* overloaded operators for <, >, ==, <=, >= operations as
needed
* in order to compare and order keys if needed by dictionaries
and
* hash tables using a KeyValuePair.
*
* @value key The key for a key/value pair item/association.
* @value value The value for a key/value pair, usually
something like
* a record (a class or struct of data we are hashing or keeping
in
* a dictionary).
*/
template <class Key, class Value>
class KeyValuePair
{
private:
Key myKey;
Value myValue;
public:
// constructors
KeyValuePair();
KeyValuePair(Key key, Value value);
// accessors, getters and setters
Key key();
void setKey(Key key);
Value& value();
};
#include "KeyValuePair.cpp"
#endif // KEYVALUEPAIR_HPP

More Related Content

Similar to Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx

Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
carliotwaycave
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Unit 4
Unit 4Unit 4
Unit 4siddr
 
The Ring programming language version 1.6 book - Part 85 of 189
The Ring programming language version 1.6 book - Part 85 of 189The Ring programming language version 1.6 book - Part 85 of 189
The Ring programming language version 1.6 book - Part 85 of 189
Mahmoud Samir Fayed
 
Quiz 9
Quiz 9Quiz 9
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
C
CC
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
Thierry Gayet
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212
Mahmoud Samir Fayed
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3Mohamed Ahmed
 
Computer Science Assignment Help
 Computer Science Assignment Help  Computer Science Assignment Help
Computer Science Assignment Help
Programming Homework Help
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
RashidFaridChishti
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
C++ Homework Help
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
ssuser454af01
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
exxonzone
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
arjurakibulhasanrrr7
 

Similar to Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx (20)

Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxInstruction1. Please read the two articles. (Kincheloe part 1 &.docx
Instruction1. Please read the two articles. (Kincheloe part 1 &.docx
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Unit 4
Unit 4Unit 4
Unit 4
 
The Ring programming language version 1.6 book - Part 85 of 189
The Ring programming language version 1.6 book - Part 85 of 189The Ring programming language version 1.6 book - Part 85 of 189
The Ring programming language version 1.6 book - Part 85 of 189
 
Quiz 9
Quiz 9Quiz 9
Quiz 9
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
C
CC
C
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212
 
C++ Course - Lesson 3
C++ Course - Lesson 3C++ Course - Lesson 3
C++ Course - Lesson 3
 
Computer Science Assignment Help
 Computer Science Assignment Help  Computer Science Assignment Help
Computer Science Assignment Help
 
Object Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptxObject Oriented Programming using C++: Ch10 Pointers.pptx
Object Oriented Programming using C++: Ch10 Pointers.pptx
 
CPP Programming Homework Help
CPP Programming Homework HelpCPP Programming Homework Help
CPP Programming Homework Help
 
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docxfilesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
filesHeap.h#ifndef HEAP_H#define HEAP_H#includ.docx
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 

More from braycarissa250

1.Does BPH predispose this patient to cancer2. Why are pati.docx
1.Does BPH predispose this patient to cancer2. Why are pati.docx1.Does BPH predispose this patient to cancer2. Why are pati.docx
1.Does BPH predispose this patient to cancer2. Why are pati.docx
braycarissa250
 
1.Do you think that mass media mostly reflects musical taste, or.docx
1.Do you think that mass media mostly reflects musical taste, or.docx1.Do you think that mass media mostly reflects musical taste, or.docx
1.Do you think that mass media mostly reflects musical taste, or.docx
braycarissa250
 
1.Discuss theoretical and conceptual frameworks. How are the.docx
1.Discuss theoretical and conceptual frameworks. How are the.docx1.Discuss theoretical and conceptual frameworks. How are the.docx
1.Discuss theoretical and conceptual frameworks. How are the.docx
braycarissa250
 
1.Discuss the medical model of corrections. Is this model of c.docx
1.Discuss the medical model of corrections. Is this model of c.docx1.Discuss the medical model of corrections. Is this model of c.docx
1.Discuss the medical model of corrections. Is this model of c.docx
braycarissa250
 
1.Discussion Question How do we perceive sacred spaceplace in Ame.docx
1.Discussion Question How do we perceive sacred spaceplace in Ame.docx1.Discussion Question How do we perceive sacred spaceplace in Ame.docx
1.Discussion Question How do we perceive sacred spaceplace in Ame.docx
braycarissa250
 
1.Cybercriminals use many different types of malware to attack s.docx
1.Cybercriminals use many different types of malware to attack s.docx1.Cybercriminals use many different types of malware to attack s.docx
1.Cybercriminals use many different types of malware to attack s.docx
braycarissa250
 
1.Define emotional intelligence. What are the benefits of emotional .docx
1.Define emotional intelligence. What are the benefits of emotional .docx1.Define emotional intelligence. What are the benefits of emotional .docx
1.Define emotional intelligence. What are the benefits of emotional .docx
braycarissa250
 
1.Define Strategic Planning and Swot Analysis2.List and define.docx
1.Define Strategic Planning and Swot Analysis2.List and define.docx1.Define Strategic Planning and Swot Analysis2.List and define.docx
1.Define Strategic Planning and Swot Analysis2.List and define.docx
braycarissa250
 
1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx
1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx
1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx
braycarissa250
 
1.Being sure that one has the resources necessary to accomplish the .docx
1.Being sure that one has the resources necessary to accomplish the .docx1.Being sure that one has the resources necessary to accomplish the .docx
1.Being sure that one has the resources necessary to accomplish the .docx
braycarissa250
 
1.Based on how you will evaluate your EBP project, which indepen.docx
1.Based on how you will evaluate your EBP project, which indepen.docx1.Based on how you will evaluate your EBP project, which indepen.docx
1.Based on how you will evaluate your EBP project, which indepen.docx
braycarissa250
 
1.Be organized. 2.   Spend less time doing a summary, but more o.docx
1.Be organized. 2.   Spend less time doing a summary, but more o.docx1.Be organized. 2.   Spend less time doing a summary, but more o.docx
1.Be organized. 2.   Spend less time doing a summary, but more o.docx
braycarissa250
 
1.After discussion with your preceptor, name one financial aspec.docx
1.After discussion with your preceptor, name one financial aspec.docx1.After discussion with your preceptor, name one financial aspec.docx
1.After discussion with your preceptor, name one financial aspec.docx
braycarissa250
 
1.A 52-year-old obese Caucasian male presents to the clinic wit.docx
1.A 52-year-old obese Caucasian male presents to the clinic wit.docx1.A 52-year-old obese Caucasian male presents to the clinic wit.docx
1.A 52-year-old obese Caucasian male presents to the clinic wit.docx
braycarissa250
 
1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx
1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx
1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx
braycarissa250
 
1.4 Participate in health care policy development to influence nursi.docx
1.4 Participate in health care policy development to influence nursi.docx1.4 Participate in health care policy development to influence nursi.docx
1.4 Participate in health care policy development to influence nursi.docx
braycarissa250
 
1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx
1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx
1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx
braycarissa250
 
1.5 Pages on the following topics Diversity, Race and Gender Equity.docx
1.5 Pages on the following topics Diversity, Race and Gender Equity.docx1.5 Pages on the following topics Diversity, Race and Gender Equity.docx
1.5 Pages on the following topics Diversity, Race and Gender Equity.docx
braycarissa250
 
1.0. Introduction Effective project management is consid.docx
1.0. Introduction Effective project management is consid.docx1.0. Introduction Effective project management is consid.docx
1.0. Introduction Effective project management is consid.docx
braycarissa250
 
1.1 What is the OSI security architecture1.2 What is the differ.docx
1.1 What is the OSI security architecture1.2 What is the differ.docx1.1 What is the OSI security architecture1.2 What is the differ.docx
1.1 What is the OSI security architecture1.2 What is the differ.docx
braycarissa250
 

More from braycarissa250 (20)

1.Does BPH predispose this patient to cancer2. Why are pati.docx
1.Does BPH predispose this patient to cancer2. Why are pati.docx1.Does BPH predispose this patient to cancer2. Why are pati.docx
1.Does BPH predispose this patient to cancer2. Why are pati.docx
 
1.Do you think that mass media mostly reflects musical taste, or.docx
1.Do you think that mass media mostly reflects musical taste, or.docx1.Do you think that mass media mostly reflects musical taste, or.docx
1.Do you think that mass media mostly reflects musical taste, or.docx
 
1.Discuss theoretical and conceptual frameworks. How are the.docx
1.Discuss theoretical and conceptual frameworks. How are the.docx1.Discuss theoretical and conceptual frameworks. How are the.docx
1.Discuss theoretical and conceptual frameworks. How are the.docx
 
1.Discuss the medical model of corrections. Is this model of c.docx
1.Discuss the medical model of corrections. Is this model of c.docx1.Discuss the medical model of corrections. Is this model of c.docx
1.Discuss the medical model of corrections. Is this model of c.docx
 
1.Discussion Question How do we perceive sacred spaceplace in Ame.docx
1.Discussion Question How do we perceive sacred spaceplace in Ame.docx1.Discussion Question How do we perceive sacred spaceplace in Ame.docx
1.Discussion Question How do we perceive sacred spaceplace in Ame.docx
 
1.Cybercriminals use many different types of malware to attack s.docx
1.Cybercriminals use many different types of malware to attack s.docx1.Cybercriminals use many different types of malware to attack s.docx
1.Cybercriminals use many different types of malware to attack s.docx
 
1.Define emotional intelligence. What are the benefits of emotional .docx
1.Define emotional intelligence. What are the benefits of emotional .docx1.Define emotional intelligence. What are the benefits of emotional .docx
1.Define emotional intelligence. What are the benefits of emotional .docx
 
1.Define Strategic Planning and Swot Analysis2.List and define.docx
1.Define Strategic Planning and Swot Analysis2.List and define.docx1.Define Strategic Planning and Swot Analysis2.List and define.docx
1.Define Strategic Planning and Swot Analysis2.List and define.docx
 
1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx
1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx
1.Choose a writer; indicate hisher contribution to the Harlem Renai.docx
 
1.Being sure that one has the resources necessary to accomplish the .docx
1.Being sure that one has the resources necessary to accomplish the .docx1.Being sure that one has the resources necessary to accomplish the .docx
1.Being sure that one has the resources necessary to accomplish the .docx
 
1.Based on how you will evaluate your EBP project, which indepen.docx
1.Based on how you will evaluate your EBP project, which indepen.docx1.Based on how you will evaluate your EBP project, which indepen.docx
1.Based on how you will evaluate your EBP project, which indepen.docx
 
1.Be organized. 2.   Spend less time doing a summary, but more o.docx
1.Be organized. 2.   Spend less time doing a summary, but more o.docx1.Be organized. 2.   Spend less time doing a summary, but more o.docx
1.Be organized. 2.   Spend less time doing a summary, but more o.docx
 
1.After discussion with your preceptor, name one financial aspec.docx
1.After discussion with your preceptor, name one financial aspec.docx1.After discussion with your preceptor, name one financial aspec.docx
1.After discussion with your preceptor, name one financial aspec.docx
 
1.A 52-year-old obese Caucasian male presents to the clinic wit.docx
1.A 52-year-old obese Caucasian male presents to the clinic wit.docx1.A 52-year-old obese Caucasian male presents to the clinic wit.docx
1.A 52-year-old obese Caucasian male presents to the clinic wit.docx
 
1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx
1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx
1.1Arguments, Premises, and ConclusionsHow Logical Are You·.docx
 
1.4 Participate in health care policy development to influence nursi.docx
1.4 Participate in health care policy development to influence nursi.docx1.4 Participate in health care policy development to influence nursi.docx
1.4 Participate in health care policy development to influence nursi.docx
 
1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx
1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx
1.5 - 2 pages single-spaced. Use 1-inch margins, 12 font, Microsoft .docx
 
1.5 Pages on the following topics Diversity, Race and Gender Equity.docx
1.5 Pages on the following topics Diversity, Race and Gender Equity.docx1.5 Pages on the following topics Diversity, Race and Gender Equity.docx
1.5 Pages on the following topics Diversity, Race and Gender Equity.docx
 
1.0. Introduction Effective project management is consid.docx
1.0. Introduction Effective project management is consid.docx1.0. Introduction Effective project management is consid.docx
1.0. Introduction Effective project management is consid.docx
 
1.1 What is the OSI security architecture1.2 What is the differ.docx
1.1 What is the OSI security architecture1.2 What is the differ.docx1.1 What is the OSI security architecture1.2 What is the differ.docx
1.1 What is the OSI security architecture1.2 What is the differ.docx
 

Recently uploaded

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 

Recently uploaded (20)

"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 

Assignment 13assg-13.cppAssignment 13assg-13.cpp   @auth.docx

  • 1. Assignment 13/assg-13.cppAssignment 13/assg-13.cpp/** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Assignment 13 Dictionaries and Hash table * implementations. */ #include<cassert> #include<iostream> #include"KeyValuePair.hpp" #include"Employee.hpp" #include"HashDictionary.hpp" usingnamespace std; /** main * The main entry point for this program. Execution of this pro gram * will begin with this main function. * * @param argc The command line argument count which is the number of * command line arguments provided by user when they starte d * the program. * @param argv The command line arguments, an array of chara cter * arrays.
  • 2. * * @returns An int value indicating program exit status. Usuall y 0 * is returned to indicate normal exit and a non-zero value * is returned to indicate an error condition. */ int main(int argc,char** argv) { // ----------------------------------------------------------------------- cout <<"----- testing Employee record and KeyValuePair class ----------- "<< endl; KeyValuePair<int, string> pair(42,"blue"); cout <<"test key: "<< pair.key()<< endl; assert(pair.key()==42); cout <<"test value: "<< pair.value()<< endl; assert(pair.value()=="blue"); int id =3; Employee e(id,"Derek Harter","1234 Main Street, Commerce T X",12345.67); cout << e << endl; assert(e.getId()==3); assert(e.getName()=="Derek Harter"); cout << endl; // ----------------------------------------------------------------------- cout <<"-------------- testing quadratic probing ------------------ -----"<< endl; constint TABLE_SIZE =7; HashDictionary<int,Employee> dict(TABLE_SIZE, EMPTY_E MPLOYEE_ID); cout <<"Newly created hash dictionary should be empty, size: "<< dict.size()<< endl;
  • 3. assert(dict.size()==0); int probeIndex =0; //cout << "probe index: " << probeIndex // << " returned probe value: " << dict.probe(id, probeIndex) // << endl; //assert(dict.probe(id, probeIndex) == 2); probeIndex =1; //cout << "probe index: " << probeIndex // << " returned probe value: " << dict.probe(id, probeIndex) // << endl; //assert(dict.probe(id, probeIndex) == 5); probeIndex =5; //cout << "probe index: " << probeIndex // << " returned probe value: " << dict.probe(id, probeIndex) // << endl; //assert(dict.probe(id, probeIndex) == 37); cout << endl; // ----------------------------------------------------------------------- cout <<"-------------- testing mid-square hashing --------------- -------"<< endl; // the following asserts will only work for 32 bit ints, leave asse rts // commented out if you have 64 bit asserts cout <<"Assuming 32 bit (4 byte) ints for these tests: "<<sizeo f(int)<< endl; assert(sizeof(int)==4); //id = 3918; //cout << "hash key: " << id // << " returned hash value: " << dict.hash(id) // << endl;
  • 4. //assert(dict.hash(id) == 1); //id = 48517; //cout << "hash key: " << id // << " returned hash value: " << dict.hash(id) // << endl; //assert(dict.hash(id) == 6); //id = 913478; //cout << "hash key: " << id // << " returned hash value: " << dict.hash(id) // << endl; //assert(dict.hash(id) == 5); //id = 8372915; //cout << "hash key: " << id // << " returned hash value: " << dict.hash(id) // << endl; //assert(dict.hash(id) == 4); // test that the distribution of the hash values // over the possible slots/buckets looks relatively // evenly distributed int counts[TABLE_SIZE]={0}; //for (id = 0; id < 1000000; id++) //{ // int hash = dict.hash(id); // counts[hash]++; //} // display results int sum =0; for(int slot =0; slot < TABLE_SIZE; slot++) { cout <<"counts for slot["<< slot <<"] = " << counts[slot]<< endl;
  • 5. sum = sum + counts[slot]; } // spot check results //assert(sum == 1000000); //assert(counts[0] == 143055); //assert(counts[6] == 142520); cout << endl; // ----------------------------------------------------------------------- cout <<"-------------- testing dictionary insertion --------------- -----"<< endl; id =438901234; //dict.insert(id, Employee(id, "Derek Harter", "123 Main St. Co mmerce TX", 58.23)); id =192834192; //dict.insert(id, Employee(id, "Alice White", "384 Bois'darc. Ca mpbell TX", 45.45)); id =998439281; //dict.insert(id, Employee(id, "Bob Green", "92 Washington Apt . 5 Greenville TX", 16.00)); id =362817371; //dict.insert(id, Employee(id, "Carol Black", "8913 FM 24 Coop er TX", 28.50)); cout <<"After inserting "<< dict.size()<<" employees:"<< endl ; cout << dict << endl; // spot check that hash table entries were correctly performed //assert(dict.size() == 4); //assert(dict[3].key() == 192834192); //assert(dict[3].value().getName() == "Alice White"); //assert(dict[1].key() == 438901234); //assert(dict[1].value().getName() == "Derek Harter"); cout << endl;
  • 6. // ----------------------------------------------------------------------- cout <<"-------------- testing dictionary search ------------------ -----"<< endl; id =438901234; //e = dict.find(id); //cout << "Search for id: " << id << endl; //cout << " Found employee: " << e << endl; //assert(e.getId() == id); //assert(e.getName() == "Derek Harter"); id =362817371; //e = dict.find(id); //cout << "Search for id: " << id << endl; //cout << " Found employee: " << e << endl; //assert(e.getId() == id); //assert(e.getName() == "Carol Black"); id =239481432; //e = dict.find(id); //cout << "Unsuccessful Search for id: " << id << endl; //cout << " Found employee: " << e << endl; //assert(e.getId() == EMPTY_EMPLOYEE_ID); //assert(e.getName() == ""); cout << endl; // return 0 to indicate successful completion return0; } Assignment 13/assg-13.pdf Assg 13: Dictionaries and Hashing
  • 7. COSC 2336 Spring 2019 April 18, 2019 Dates: Due: Sunday May 05, by Midnight Objectives • More practice with using class templates • Learn about implementing and using key/value pair Dictionary ab- straction • Implement and learn about some basic hashing techniques, like mid- square hasing and quadratic probing for closed hashing schemes. Description In this assignment you will be implementing some basic mechanisms of a hash table to implement a Dictionary that uses hashing to store and search for items in its collection. You have been given many files for this assign- ment. I have provided an Employee class in "Employee.[hpp|cpp]" and a KeyValuePair class in "KeyValuePair.[hpp|cpp]". You will not need to make any changes to these files or classes, they should work as given for this as-
  • 8. signment. You will be adding and implementing some member functions to the HashDictionary class. The initial "HashDictionary.[hpp|cpp]" file contains a constructor and destructor for a HashDictionary as well as some other accessors and operators already implemented that are used for testing. You will be implementing a closed hash table mechanism using quadratic probing of the slots. You will also implement a version of the mid-square 1 hashing function described in our textbook (Shaffer section 9.4.3 on closed hashing mechinsms). For this assignment you need to perform the following tasks. 1. Your first task is to implement methods to define the probe sequence for closed hasing. Add a member function named probe() to the HashDictionary class. Be aware that the HashDictionary class is a templatized on <Key, Value> templates, thus when you implement the class methods you need to templatize the class methods correctly. You can look at the example implementations of size() and the con-
  • 9. structors to remind yourself how to do this correctly. In any case, probe() is a member function that takes two parameters, a Key and an integer index value. We are not using secondary hashing (as described in our textbook) so the Key value will actually not be used in your function. However, keep it as a parameter as the gen- eral abstraction/API for the probe function should include it for cases where secondary hashing is used. probe() should be a const class member function, as calling it does not change the dictionary. Finally probe() will return an ineger as its result. Your probe() funciton should implement a quadratic probing scheme as described in our Shaffer textbook section 9.4.3 on pg. 338. Use c1 = 1, c2 =2, c3 = 2 as the parameters for your quadratic probe (the tests of probe() assume your probe sequence is using these pa- rameter values for the quadratic function). 2. You second tasks is to implement a hash function for integer like keys using the described mid-square hasing function (Shaffer 9.4.1 Example 9.6 pg. 327). We will create a slight variation of this algorithm for our hashing dictionary. First of all the hash() member functions should take a Key as its only input parameter, and it will then return a
  • 10. regular int as its result. Since this is a hash function, the integer value should be in the range 0 - tableSize-1, so don’t forget to mod by the tableSize before returning your hash result. hash() should work like this. First of all, you should square the key value that is passed in. Then, assuming we are working with a 32 bit int, we want to only keep the middle 16 bits of the square of the key to use for our hash. There are many ways to work with and get the bits you need, but most likely you will want to use C bitwise operators to do this. For example, a simple method to get the middle 16 bits is 2 to first mask out the upper 8 bits using the bitwise & operator (e.g. key & 0x00FFFFFF) will mask out the high order 8 bits to 0). Then once you have removed the upper most significant 8 bits, you can left shift the key by 8 bits, thus dropping out the lower least significant 8 bits (e.g. key >> 8). Performing a mask of the upper 8 bits and shifting out the lower 8 bits will result in you only retaining the middle 16 bits.
  • 11. If your system is using 64 bit integers rather than 32 bit integers, perform the mid-square method but retain the middle 32 bits of the result. You can use the sizeof(int) method to determine how many bytes are in an int on your system. I will give a bonus point if you write your hash() function to correctly work for both 32 and 64 bit values by testing sizeof(int) and doing the appopriate work to get the middle bits. Again after you square the key and get the middle bits, make sure you modulo the result to get an actual has index in the correct range. 3. The third task is to add the insert() method to your HashDictionary so that you can insert new key/value pairs into the dictionary. insert() should take a constant Key reference and a constant Value reference as its input parameters (note that both of these parameters should be declared as const, and they should both be reference pa- rameters, so use the & to indicate they are passed by reference). Your insert() function does not return a result, so it will be a void func- tion. The algorithm for insert is described in Shaffer 9.4.3 on pg. 334. You need to call and use the probe() and hash() funciton you created
  • 12. in the first 2 steps to correctly define/implement your closed hashing probe sequence. The basica algorithm is that you use hash() to de- termine the initial home slot, and probe() gives an offset you should add. Basically you have to search the hashTable using the probe se- quence until you find an empty slot. Once you find an empty slot, you should create a new instance of a KeyValuePair<Key, Value> object, that contains the key and value that were provided as input param- eters to your insert() function. This KeyValuePair instance should then be inserted into the table at the location where you find the first empty slot on the probe sequence. Also don’t forget to update the valueCount paramemter of the HashDictionary class that keeps track of the number of items currently in the dictionary. 3 4. Finally you will also implement the find() method to search for a particular key in your dictionary. The find() member function taks a single Key parameter as input (it should be a const Key& reference parameter). The find() functin will return a Value as a result, which
  • 13. will be the Value of the record associated with the given Key if it was found in the dictionary, or an empty Value() object if it was not found. The find() method uses the same probe sequence as insert() imple- mented by your probe() and hash() methods. So you should again search along the probe sequence, until you either find the key you were given to search for, or else find an empty slot. Then at the end, if you found the key in the hashTable you should return the value that corresponds to the key that was searched for. If the search failed and you found an empty slot on your probe sequence, you should instead return an empty Value() object, which is used as an indicator for a failed search. In this assignment you will be given a lot of starting code. As usual, there is an "assg-13.cpp" file which contains commented out tests of the code/functions you are to write. You have been given and "Em- ployee.[hpp|cpp]" file containing a simple definition of a (non- templated) class/record that holds a few pieces of information about a theoretical Employee. We use this class to create a hash dictionary for testing with the employee id as the key, and the Employee record as the associated value
  • 14. in our Dictionary. You have also been given a template class in the file "KeyValuePair.[hpp|cpp]". This contains a templatized container to holding a key/value pair of items. You will not need to add any code or make any changes in the Employee or KeyValuePair class files. You have also been given a "HashDictionary.[hpp|cpp]" file containing beginning defintions of a HashDictionary class. The member functions you need to add for this assignment should be added to these files. Here is an example of the output you should get if your code is passing all of the tests and is able to run the simulation. You may not get the exact same statistics for the runSimulation() output, as the simulation is generating random numbers, but you should see similar values. ----- testing Employee record and KeyValuePair class ----------- test key: 42 test value: blue ( id: 3, Derek Harter, 1234 Main Street, Commerce TX, 12345.67 ) 4 -------------- testing quadratic probing ----------------------- Newly created hash dictionary should be empty, size: 0 probe index: 0 returned probe value: 2 probe index: 1 returned probe value: 5
  • 15. probe index: 5 returned probe value: 37 -------------- testing mid-square hashing ---------------------- Assuming 32 bit (4 byte) ints for these tests: 4 hash key: 3918 returned hash value: 1 hash key: 48517 returned hash value: 6 hash key: 913478 returned hash value: 5 hash key: 8372915 returned hash value: 4 counts for slot[0] = 143055 counts for slot[1] = 143040 counts for slot[2] = 143362 counts for slot[3] = 142399 counts for slot[4] = 142966 counts for slot[5] = 142658 counts for slot[6] = 142520 -------------- testing dictionary insertion -------------------- After inserting 4 employees: Slot: 0 Key : 362817371 Value: ( id: 362817371, Carol Black, 8913 FM 24 Cooper TX, 28.50 ) Slot: 1 Key : 438901234 Value: ( id: 438901234, Derek Harter, 123 Main St. Commerce TX, 58.23 ) Slot: 2 Key : 0 Value: ( id: 0, , , 0.00 ) Slot: 3 Key : 192834192 Value: ( id: 192834192, Alice White, 384 Bois'darc. Campbell
  • 16. TX, 45.45 ) Slot: 4 5 Key : 998439281 Value: ( id: 998439281, Bob Green, 92 Washington Apt. 5 Greenville TX, 16.00 ) Slot: 5 Key : 0 Value: ( id: 0, , , 0.00 ) Slot: 6 Key : 0 Value: ( id: 0, , , 0.00 ) -------------- testing dictionary search ----------------------- Search for id: 438901234 Found employee: ( id: 438901234, Derek Harter, 123 Main St. Commerce TX, 58.23 ) Search for id: 362817371 Found employee: ( id: 362817371, Carol Black, 8913 FM 24 Cooper TX, 28.50 ) Unsuccessful Search for id: 239481432 Found employee: ( id: 0, , , 0.00 ) Assignment Submission A MyLeoOnline submission folder has been created for this
  • 17. assignment. You should attach and upload your completed "HashDictionary.[hpp|cpp]" source files to the submission folder to complete this assignment. You do not need to submit your "assg-13.cpp" file with the tests, nor the Employee or KeyVal- uePair files, since you should not have made changes to any of these (except to uncomment out the tests in assg-13.cpp). Please only submit the asked for source code files, I do not need your build projects, executables, project files, etc. 6 Requirements and Grading Rubrics Program Execution, Output and Functional Requirements 1. Your program must compile, run and produce some sort of output to be graded. 0 if not satisfied. 2. (20 pts.) probe() member function implemented. Function is using quadratic probing as asked for, with correct values for c1, c2 and c3 parameters. Probe sequence appears correct and passes tests. 3. (20 pts.) hash() member function implemented correctly. Function implements the mid-square method as described. Function
  • 18. correctly uses only the 16 middle bits if system uses 32 bit integers. 4. (30 pts.) insert() member function implemented and working. Func- tion appears to be correctly generating probe sequence using the probe() and hash() functions. Items are correctly inserted into ex- pected location in the hash table. 5. (30 pts.) find() member function implemented and working. Function appears to be also correctly using the probe sequence in the same was as insert(). Function passes the expected tests. Program Style Your programs must conform to the style and formatting guidelines given for this class. The following is a list of the guidelines that are required for the assignment to be submitted this week. 1. Most importantly, make sure you figure out how to set your indentation settings correctly. All programs must use 2 spaces for all indentation levels, and all indentation levels must be correctly indented. Also all tabs must be removed from files, and only 2 spaces used for indentation. 2. A function header must be present for member functions you define. You must give a short description of the function, and document
  • 19. all of the input parameters to the function, as well as the return value and data type of the function if it returns a value for the member functions, just like for regular functions. However, setter and getter methods do not require function headers. 7 3. You should have a document header for your class. The class header document should give a description of the class. Also you should doc- ument all private member variables that the class manages in the class document header. 4. Do not include any statements (such as system("pause") or inputting a key from the user to continue) that are meant to keep the terminal from going away. Do not include any code that is specific to a single operating system, such as the system("pause") which is Microsoft Windows specific. 8 Assignment 13/Employee.cppAssignment 13/Employee.cpp/** * @author Jane Programmer
  • 20. * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Simple example of an Employee record/class * we can use to demonstrate HashDictionary key/value pair * management. */ #include<string> #include<iostream> #include<iomanip> #include<sstream> #include"Employee.hpp" usingnamespace std; /** constructor * Default constructor for our Employee record/class. Construct an * empty employee record */ Employee::Employee() { this->id = EMPTY_EMPLOYEE_ID; this->name =""; this->address =""; this->salary =0.0; } /** constructor * Basic constructor for our Employee record/class. */ Employee::Employee(int id, string name, string address,float sal
  • 21. ary) { this->id = id; this->name = name; this->address = address; this->salary = salary; } /** id accessor * Accessor method to get the employee id. * * @returns int Returns the integer employee id value. */ intEmployee::getId()const { return id; } /** name accessor * Accessor method to get the employee name. * * @returns string Returns the string containing the full * employee name for this record. */ string Employee::getName()const { return name; } /** overload operator<< * Friend function to ouput representation of Employee to an * output stream. *
  • 22. * @param out A reference to an output stream to which we sho uld * send the representation of an employee record for display. * @param employee The reference to the employee record to be displayed. * * @returns ostream& Returns a reference to the original output * stream, but now the employee information should have been * inserted into the stream for display. */ ostream&operator<<(ostream& out,Employee& employee) { //out << "Employee id: " << employee.id << endl // << " name : " << employee.name << endl // << " address: " << employee.address << endl // << " salary : " << fixed << setprecision(2) << employee.s alary << endl; out <<"( id: "<< employee.id <<", " << employee.name <<", " << employee.address <<", " << fixed << setprecision(2)<< employee.salary <<" )"<< endl; return out; } Assignment 13/Employee.hpp /** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Simple example of an Employee record/class
  • 23. * we can use to demonstrate HashDictionary key/value pair * management. */ #include <string> #include <iostream> using namespace std; #ifndef EMPLOYEE_HPP #define EMPLOYEE_HPP // This should really be a class constant, however this // global constant represents a flag that is used to // indicate empty slots and/or failed search. const int EMPTY_EMPLOYEE_ID = 0; /** Employee * A simple Employee class/record to demonstrate/test * our hashing dictionary assignment. * NOTE: we are using 0 as a flag to represent an unused * slot or an invalid/empty employee. This is used/assumed * by our dictionary class to determine if a slot is empty * and/or to give a failure result for a failed search. */ class Employee { private: int id; string name; string address; float salary; public: Employee(); Employee(int id, string name, string address, float salary);
  • 24. int getId() const; string getName() const; friend ostream& operator<<(ostream& out, Employee& employee); }; #endif // EMPLOYEE_HPP Assignment 13/HashDictionary.cppAssignment 13/HashDictionary.cpp/** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Template class for definining a dictionary * that uses a hash table of KeyValuePair items. * Based on Shaffer hashdict implementation pg. 340 */ /** constructor * Standard constructor for the HashDictionary * * @param tableSize The size of the hash table that should be * generated for internal use by this dictionary for hasing. * @param emptyKey A special flag/value that can be used to d etect * invalid/unused keys. We need this so we can indicate which * slots/buckets in our hash table are currently empty, and also * this value is used as a return result when an unsuccessful
  • 25. * search is performed on the dictionary. */ template<classKey,classValue> HashDictionary<Key,Value>::HashDictionary(int tableSize,Key emptyKey) { this->tableSize = tableSize; this->EMPTYKEY = emptyKey; valueCount =0; // allocate an array/table of the indicated initial size hashTable =newKeyValuePair<Key,Value>[tableSize]; // initialize the hash table so all slots are initially empty for(int index =0; index < tableSize; index++) { hashTable[index].setKey(EMPTYKEY); } } /** destructor * Standard destructor for the HashDictionary. Be good memor y managers and * free up the dynamically allocated array of memory pointed to by hashTable. */ template<classKey,classValue> HashDictionary<Key,Value>::~HashDictionary() { delete[] hashTable; } /** size * Accessor method to get the current size of this dictionary,
  • 26. * e.g. the count of the number of key/value pairs currently bein g * managed in our hash table. * * @returns in Returns the current number of items being manag ed by * this dictionary and currently in our hashTable. */ template<classKey,classValue> intHashDictionary<Key,Value>::size()const { return valueCount; } // Place your implementations of the class methods probe(), has h(), // insert() and find() here /** overload indexing operator[] * Overload indexing operator[] to provide direct access * to hash table. This is not normally part of the Dictionary * API/abstraction, but included here for testing. * * @param index An integer index. The index should be in the r ange 0 - tablesize-1. * * @returns KeyValuePair<> Returns a KeyValuePair object if t he index into the * internal hash table is a valid index. This method throws an exception if * the index is not a valid slot of the hash table. */
  • 27. template<classKey,classValue> KeyValuePair<Key,Value>&HashDictionary<Key,Value>::oper ator[](int index) { if(index <0|| index >= tableSize) { cout <<"Error: <HashDictionary::operator[] invalid index: " << index <<" table size is currently: " << tableSize << endl; assert(false); } return hashTable[index]; } /** HashDictionary output stream operator * Friend function for HashDictionary. We normally wouldn't h ave * something like this for a Dictionary or HashTable, but for tes ting * and learning purposes, we want to be able to display the cont ents of * each slot in the hash table of a HashDictionary container. * * @param out An output stream reference into which we should insert * a representation of the given HashDictionary. * @param aDict A HashDictionary object that we want to displ ay/represent * on an output stream. * * @returns ostream& Returns a reference to the original given output stream, * but now the values representing the dictionary we were give n should
  • 28. * have been sent into the output stream. */ template<typename K,typename V> ostream&operator<<(ostream& out,constHashDictionary<K, V> & aDict) { for(int slot =0; slot < aDict.tableSize; slot++) { out <<"Slot: "<< slot << endl; out <<" Key : "<< aDict.hashTable[slot].key()<< endl; out <<" Value: "<< aDict.hashTable[slot].value()<< endl; } out << endl; return out; } Assignment 13/HashDictionary.hpp /** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Template class for definining a dictionary * that uses a hash table of KeyValuePair items. * Based on Shaffer hashdict implementation pg. 340 */ #include <cassert> #include <iostream> #include "KeyValuePair.hpp" using namespace std;
  • 29. #ifndef HASHDICTIONARY_HPP #define HASHDICTIONARY_HPP /** HashDictionary * An implementation of a dictionary that uses a hash table to insert, search * and delete a set of KeyValuePair items. In the assignment, we will be * implementing a closed hashing table with quadratic probing. The hash function * will implement a version of the mid-square hasing function described in * our Shaffer textbook. * * @value hashTable An array of KeyValuePair items, the hash table this class/container * is managing. * @value tableSize The actual size of the hashTable array * @value valueCount The number of KeyValuePair items that are currently being * managed and are contained in the hashTable * @value EMPTYKEY A special user-supplied key that can be used to indicate empty * slots. Since how we determine what is a valid/invalid key will depend on the * key type, the user must supply this special flag/value when setting up the * hash dictionary. */ template <class Key, class Value> class HashDictionary { protected: KeyValuePair<Key, Value>* hashTable; // the hash table
  • 30. int tableSize; // the size of the hash table, e.g. symbol M from textbook int valueCount; // the count of the number of value items currently in table Key EMPTYKEY; // a special user-supplied key that can be used to indicate empty slots public: // constructors and destructors HashDictionary(int tableSize, Key emptyKey); ~HashDictionary(); // accessor methods int size() const; // searching and insertion // all 4 of the methods you were required to create for this // assignment should have appropriate class method signatures // defined here. // overload operators (mostly for testing) KeyValuePair<Key, Value>& operator[](int index); template <typename K, typename V> friend ostream& operator<<(ostream& out, const HashDictionary<K, V>& aDict); }; #include "HashDictionary.cpp" #endif // HASHDICTIONARY_HPP Assignment 13/Instructions.png Assignment 13/KeyValuePair.cppAssignment
  • 31. 13/KeyValuePair.cpp/** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Template class for definining Key/Value pairs, * suitable for dictionary and hash table implementations. * Based on Shaffer KVPair ADT definition, pg. 139 Fig 4.31. */ /** constructor * Default constructor for a KeyValuePair. */ template<classKey,classValue> KeyValuePair<Key,Value>::KeyValuePair() { } /** constructor * Standard constructor for a KeyValuePair. * * @param key The key portion that is to be stored in this pair. * @param value The value portion that is to be stored in this pa ir. */ template<classKey,classValue> KeyValuePair<Key,Value>::KeyValuePair(Key key,Valuevalue) { this->myKey = key; this->myValue =value;
  • 32. } /** key accessor * Accessor method to get and return the key for this key/value pair * * @returns Key Returns an object of template type Key, which is the * key portion of the pair in this container. */ template<classKey,classValue> KeyKeyValuePair<Key,Value>::key() { return myKey; } /** key setter * Accessor method to set the key for this key/value pair * * @param key The new value to update the key to for this pair. */ template<classKey,classValue> voidKeyValuePair<Key,Value>::setKey(Key key) { this->myKey = key; } /** value accessor * Accessor method to get and return the value for this key/valu e pair. * * @returns Value& Returns a reference to the value object in th is
  • 33. * key value pair container. */ template<classKey,classValue> Value&KeyValuePair<Key,Value>::value() { return myValue; } Assignment 13/KeyValuePair.hpp /** * @author Jane Programmer * @cwid 123 45 678 * @class COSC 2336, Spring 2019 * @ide Visual Studio Community 2017 * @date April 8, 2019 * @assg Assignment 13 * * @description Template class for definining Key/Value pairs, * suitable for dictionary and hash table implementations. * Based on Shaffer KVPair ADT definition, pg. 139 Fig 4.31. */ #ifndef KEYVALUEPAIR_HPP #define KEYVALUEPAIR_HPP /** KeyValue Pair * Definition of basic key/value pair container. This container of course * associates a value (usually a record like a class or struct), with * a key (can be anything). *
  • 34. * We do not use the comparator Strategy pattern as discussed in * Shaffer pg. 144 here. We assume that the Key type has suitably * overloaded operators for <, >, ==, <=, >= operations as needed * in order to compare and order keys if needed by dictionaries and * hash tables using a KeyValuePair. * * @value key The key for a key/value pair item/association. * @value value The value for a key/value pair, usually something like * a record (a class or struct of data we are hashing or keeping in * a dictionary). */ template <class Key, class Value> class KeyValuePair { private: Key myKey; Value myValue; public: // constructors KeyValuePair(); KeyValuePair(Key key, Value value); // accessors, getters and setters Key key(); void setKey(Key key); Value& value(); };