SlideShare a Scribd company logo
1 of 18
Download to read offline
This project will implement a simple username/password lookup system using hash tables. You
should create the Hash Table from scratch. It may be helpful to create a separate class called
HashEntry, in which you can store a String username and String password. The Hash Table will
store these entries using the username as the key and the password as the value.
Create a hash code using the key to determine where the value is stored in the Hash Table. Here
is a sample hash method. Feel free to borrow it for your program:
privateint calcHashCode(String key) {
int mod = key.hashCode() % size;
return mod < 0 ? mod + size : mod;
}
You will be provided with a data file containing comma separated usernames and passwords.
Read the data in from the file and put it into the table. Once the table is populated, ask the user to
log into the system. If their username and password match the data in the table, alert the user that
access has been granted:
Login: trevor
User trevor not found.
Login: mary
Password: test
Authentication Failure
Login: mary
Password: contrary
Authentication Successful
Welcome mary
Provided Data File (containing comma separated usernames and passwords):
jack,broken.crown
jill,tumblin'down
mary,contrary
bopeep,sheep!lost
Solution
//main.cpp
#include
#include
#include
#include
#include
#include "HashTable.cpp"
using namespace std;
/// the struct for the login and password
struct Account
{
/// variables
string login;
string password;
/// hash function
static unsigned int hash(const string& str)
{
unsigned int val = 0;
for (int i = 0; i < str.length(); ++i) {
val += str[i];
}
return val;
}
/// get key function
string getKey() const
{
return login;
}
};
int main()
{
string loginI;
string passwordI;
string temp;
/// open file
ifstream fin ("password.dat");
fin.clear();
/// make new account to read into
Account acct;
/// make the hash table
HashTable data (8);
/// read in
while (fin.good())
{
fin >> acct.login >> acct.password;
//cout << acct.login << " " << acct.password << endl;
data.insert(acct);
//data.showStructure();
}
data.showStructure();
/// read in
cout << "Login: ";
cin >> loginI;
do
{
cout << "Password: ";
cin >> passwordI;
/// check for login
if (data.retrieve(loginI, acct))
{
/// check if passwords are the same
if ((acct.password == passwordI))
{
/// same password, print success
cout << "Authentication successful" << endl;
}
else
{
/// different password, print failure
cout << "Authentication failure" << endl;
}
}
else
{
/// if the data login is not saved print failure
cout << "Authentication failure" << endl;
}
cout << "Login: ";
cin >> loginI;
}
while(!cin.eof());
return 0;
}
=====================================================================
=====
#include
#include
#include
#include
#include "HashTable.h"
#include "show10.cpp"
using namespace std;
template
HashTable::HashTable(int initTableSize)
{
/// save size
tableSize = initTableSize;
/// initialize the array
dataTable = new BSTree[tableSize];
}
template
HashTable::HashTable(const HashTable& other)
{
/// copy size and create new table
tableSize = other.tableSize;
dataTable = new BSTree[tableSize];
*this = other;
}
template
HashTable& HashTable:: operator=(const HashTable& other)
{
/// if the same return
if (this = &other)
return *this;
/// clear
clear();
/// copy the size and create new table
tableSize = other.tableSize;
dataTable = new BSTree[tableSize];
/// go through tables and copy the trees
for (int i = 0; i < tableSize; ++i)
{
dataTable[i] = other.dataTable[i];
}
return *this;
}
template
HashTable::~HashTable()
{
clear();
delete[] dataTable;
}
template
void HashTable::insert(const DataType& newDataItem)
{
/// get hash
int location = newDataItem.hash(newDataItem.getKey()) % tableSize;
/// insert into tree
dataTable[location].insert(newDataItem);
}
template
bool HashTable:: remove(const KeyType& deleteKey)
{
/// get its location in the array
int location = DataType::hash(deleteKey) % tableSize;
/// check to delete it
return dataTable[location].remove(deleteKey);
}
template
bool HashTable:: retrieve(const KeyType& searchKey, DataType& returnItem) const
{
/// find location in the array
int location = DataType::hash(searchKey) % tableSize;
/// check if the item is there
return dataTable[location].retrieve(searchKey, returnItem);
}
template
void HashTable:: clear()
{
/// iterate through the complete hash table
for (int i = 0; i < tableSize; ++i)
{
dataTable[i].clear();
}
}
/**
* Not Used
*/
template
bool HashTable:: isEmpty() const
{
bool flag = true;
for (int i = 0; i < tableSize; ++i)
{
/// check to see if each tree insdie the table is empty
flag = dataTable[i].isEmpty();
/// if flag is ever turned into false, then return false
if (flag == false)
return false;
}
return true;
}
template
double HashTable:: standardDeviation() const
{
}
template
void HashTable:: copyTable(const HashTable& source)
{
*this = source;
}
==================================================
// HashTable.h
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include
#include
using namespace std;
#include "BSTree.cpp"
template
class HashTable {
public:
HashTable(int initTableSize);
HashTable(const HashTable& other);
HashTable& operator=(const HashTable& other);
~HashTable();
void insert(const DataType& newDataItem);
bool remove(const KeyType& deleteKey);
bool retrieve(const KeyType& searchKey, DataType& returnItem) const;
void clear();
bool isEmpty() const;
void showStructure() const;
double standardDeviation() const;
private:
void copyTable(const HashTable& source);
int tableSize;
BSTree* dataTable;
};
#endif // ifndef HASHTABLE_H
====================================================================
//BSTree.cpp
#include
#include
#include
#include
#include "BSTree.h"
#include "show9.cpp"
using namespace std;
template < typename DataType, class KeyType >
BSTree::BSTreeNode::BSTreeNode( const DataType& nodeDataItem, BSTreeNode *leftPtr,
BSTreeNode *rightPtr )
: dataItem(nodeDataItem), left(leftPtr), right (rightPtr)
{
}
template < typename DataType, class KeyType >
BSTree::BSTree()
{
root = NULL;
}
template < typename DataType, class KeyType >
BSTree::BSTree(const BSTree& source)
{
root=NULL;
*this = source;
}
template < typename DataType, class KeyType >
BSTree& BSTree::operator=(const BSTree& source)
{
if (this == &source)
return *this;
clear();
copyHelp(root, source.root);
return *this;
}
template < typename DataType, class KeyType >
void BSTree::copyHelp( BSTreeNode*& home, BSTreeNode* RHS )
{
/// Stopping condition, end of tree
if (RHS == NULL)
{
home = NULL;
return;
}
/// Create node
home = new BSTreeNode (RHS->dataItem, NULL, NULL);
/// Recall with the other parts of the tree
copyHelp(home->left, RHS->left);
copyHelp(home->right, RHS->right);
return;
}
template < typename DataType, class KeyType >
BSTree::~BSTree ()
{
clear();
}
template < typename DataType, class KeyType >
void BSTree::insert(const DataType& newDataItem)
{
insertHelper(root, newDataItem);
}
template < typename DataType, class KeyType >
void BSTree::insertHelper(BSTreeNode* & location, const DataType& newDataItem)
{
/// if reached location, create the new node
if (location==NULL)
location = new BSTreeNode(newDataItem, NULL, NULL);
/// if the current location is larger than data go left
if (location->dataItem.getKey() > newDataItem.getKey())
insertHelper(location->left, newDataItem);
/// if the current location is smaller than data, go right
if (location->dataItem.getKey() < newDataItem.getKey())
insertHelper(location->right, newDataItem);
}
template < typename DataType, class KeyType >
bool BSTree::retrieve(const KeyType& searchKey, DataType& searchDataItem) const
{
return retrieveHelper(root, searchKey, searchDataItem);
}
template < typename DataType, class KeyType >
bool BSTree::retrieveHelper(BSTreeNode* location, const KeyType& searchKey, DataType&
searchDataItem) const
{
/// if checked the complete tree, return false
if (location == NULL)
return false;
/// if found, return true
if (location->dataItem.getKey() == searchKey)
{
searchDataItem = location->dataItem;
return true;
}
/// if what were are looking for is smaller go left else go right
if (location->dataItem.getKey() > searchKey)
{
return retrieveHelper(location->left, searchKey, searchDataItem);
}
else
{
return retrieveHelper(location->right, searchKey, searchDataItem);
}
}
template < typename DataType, class KeyType >
bool BSTree:: remove ( const KeyType& deleteKey )
{
return removeHelper(root, deleteKey);
}
template < typename DataType, class KeyType >
bool BSTree:: removeHelper ( BSTreeNode* & location, const KeyType& deleteKey )
{
/// if at the end and not found, return false
if (location == NULL)
return false;
/// if found, delete
if (location->dataItem.getKey() == deleteKey)
{
/// if no children
if ((location->left == NULL) && (location->right == NULL))
{
delete location;
location = NULL;
return true;
}
/// if one child
/// left child, no right
if ((location->left != NULL) && (location->right == NULL))
{
BSTreeNode* temp;
temp = location;
location = location->left;
delete temp;
return true;
}
/// no left, right child
if ((location->left == NULL) && (location->right != NULL))
{
BSTreeNode* temp;
temp = location;
location = location->right;
delete temp;
return true;
}
/// if two children
if ((location->left != NULL) && (location->right != NULL))
{
BSTreeNode* temp;
temp = location;
/// get predecessor
temp = temp->left;
while (temp->right != NULL)
temp = temp->right;
/// overwrite the value to delete with the predecessor
location->dataItem = temp->dataItem;
/// delete the node with the value just written to the new location
return removeHelper(location->left, temp->dataItem.getKey());
}
}
/// keep searching
if (location->dataItem.getKey() > deleteKey)
return removeHelper(location->left, deleteKey);
else
return removeHelper(location->right, deleteKey);
}
template < typename DataType, class KeyType >
void BSTree:: writeKeys () const
{
writeKeysHelper(root);
cout << endl;
}
template < typename DataType, class KeyType >
void BSTree:: writeKeysHelper (BSTreeNode* location) const
{
if (!isEmpty())
{
/// go all the way to the left
if (location->left != NULL)
{
writeKeysHelper(location->left);
}
/// once all the way to the left print out the current
cout << location->dataItem.getKey() << " ";
/// check for the children to the right of the most left node
if (location->right != NULL)
{
writeKeysHelper(location->right);
}
}
}
template < typename DataType, class KeyType >
void BSTree:: clear()
{
clearHelper(root);
root = NULL;
}
template < typename DataType, class KeyType >
void BSTree:: clearHelper( BSTreeNode* & location )
{
if(!isEmpty())
{
/// if there is more to the left recall with child
if (location->left != NULL)
clearHelper(location->left);
/// if leftmost has a right child repeat process with the right child
if (location->right != NULL)
clearHelper(location->right);
/// deallocate
delete location;
}
}
template < typename DataType, class KeyType >
bool BSTree:: isEmpty () const
{
return (root == NULL);
}
template < typename DataType, class KeyType >
int BSTree:: getHeight () const
{
if (isEmpty())
return 0;
heightHelper(root);
}
template < typename DataType, class KeyType >
int BSTree:: heightHelper ( BSTreeNode* location) const
{
/// if we reached a null spot, return 0 since nothing is added
if (location == NULL)
return 0;
/// get the size of the left and right by recalling and going to the left and right
int leftTree = heightHelper(location->left);
int rightTree = heightHelper(location->right);
/// return which ever is larger plus one since the current node is part of the height
if (leftTree > rightTree)
return leftTree+1;
else
return rightTree+1;
}
template < typename DataType, class KeyType >
int BSTree:: getCount () const
{
return countHelper(root);
}
template < typename DataType, class KeyType >
int BSTree:: countHelper (BSTreeNode* location) const
{
if (location == NULL)
return 0;
else
return (countHelper(location->left)+countHelper(location->right)+1);
}
/**
* NOT USED
*/
template < typename DataType, class KeyType >
void BSTree:: writeLessThan ( const KeyType& searchKey ) const
{
}
==================================================================
//BSTree.h
#ifndef BSTREE_H
#define BSTREE_H
#include
#include
using namespace std;
template < typename DataType, class KeyType > // DataType : tree data item
class BSTree // KeyType : key field
{
public:
// Constructor
BSTree (); // Default constructor
BSTree ( const BSTree& other ); // Copy constructor
BSTree& operator= ( const BSTree& other );
// Overloaded assignment operator
// Destructor
~BSTree ();
// Binary search tree manipulation operations
void insert ( const DataType& newDataItem ); // Insert data item
bool retrieve ( const KeyType& searchKey, DataType& searchDataItem ) const;
// Retrieve data item
bool remove ( const KeyType& deleteKey ); // Remove data item
void writeKeys () const; // Output keys
void clear (); // Clear tree
// Binary search tree status operations
bool isEmpty () const; // Tree is empty
// !! isFull() has been retired. Not very useful in a linked structure.
// Output the tree structure -- used in testing/debugging
void showStructure () const;
// In-lab operations
int getHeight () const; // Height of tree
int getCount () const; // Number of nodes in tree
void writeLessThan ( const KeyType& searchKey ) const; // Output keys < searchKey
protected:
class BSTreeNode // Inner class: facilitator for the BSTree class
{
public:
// Constructor
BSTreeNode ( const DataType &nodeDataItem, BSTreeNode *leftPtr, BSTreeNode *rightPtr );
// Data members
DataType dataItem; // Binary search tree data item
BSTreeNode *left, // Pointer to the left child
*right; // Pointer to the right child
};
// Recursive helpers for the public member functions -- insert
// prototypes of these functions here.
void showHelper ( BSTreeNode *p, int level ) const;
void insertHelper(BSTreeNode* & location, const DataType& newDataItem);
bool retrieveHelper(BSTreeNode* location, const KeyType& searchKey, DataType&
searchDataItem) const;
bool removeHelper ( BSTreeNode* & location, const KeyType& deleteKey );
void writeKeysHelper (BSTreeNode* location) const;
void clearHelper( BSTreeNode* & location );
int heightHelper ( BSTreeNode* location) const;
int countHelper (BSTreeNode* location) const;
void copyHelp( BSTreeNode*& home, BSTreeNode* RHS );
// Data member
BSTreeNode *root; // Pointer to the root node
};
#endif // define BSTREE_H
=====================================================================
=
//show9.cpp
template < typename DataType, typename KeyType >
void BSTree:: showStructure () const
{
if ( root == 0 )
cout << "Empty tree" << endl;
else
{
cout << endl;
showHelper(root,1);
cout << endl;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template < typename DataType, typename KeyType >
void BSTree:: showHelper ( BSTreeNode *p,
int level ) const
{
int j; // Loop counter
if ( p != 0 )
{
showHelper(p->right,level+1); // Output right subtree
for ( j = 0 ; j < level ; j++ ) // Tab over to level
cout << "t";
cout << " " << p->dataItem.getKey(); // Output key
if ( ( p->left != 0 ) && // Output "connector"
( p->right != 0 ) )
cout << "<";
else if ( p->right != 0 )
cout << "/";
else if ( p->left != 0 )
cout << "";
cout << endl;
showHelper(p->left,level+1); // Output left subtree
}
}
======================================================

More Related Content

Similar to This project will implement a simple usernamepassword lookup system.pdf

Given the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfGiven the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfaucmistry
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI yogita kachve
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus
 
Shared_memory_hash_table
Shared_memory_hash_tableShared_memory_hash_table
Shared_memory_hash_tableRussell Childs
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesJeremy Green
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docxAustinaGRPaigey
 
maincpp Build and procees a sorted linked list of Patie.pdf
maincpp   Build and procees a sorted linked list of Patie.pdfmaincpp   Build and procees a sorted linked list of Patie.pdf
maincpp Build and procees a sorted linked list of Patie.pdfadityastores21
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfarjuncollection
 
Cassandra Day London 2015: Getting Started with Apache Cassandra and Java
Cassandra Day London 2015: Getting Started with Apache Cassandra and JavaCassandra Day London 2015: Getting Started with Apache Cassandra and Java
Cassandra Day London 2015: Getting Started with Apache Cassandra and JavaDataStax Academy
 
Cassandra Day London: Building Java Applications
Cassandra Day London: Building Java ApplicationsCassandra Day London: Building Java Applications
Cassandra Day London: Building Java ApplicationsChristopher Batey
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 

Similar to This project will implement a simple usernamepassword lookup system.pdf (20)

Given the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfGiven the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdf
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
 
Shared_memory_hash_table
Shared_memory_hash_tableShared_memory_hash_table
Shared_memory_hash_table
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta Boxes
 
please code in c#- please note that im a complete beginner- northwind.docx
please code in c#- please note that im a complete beginner-  northwind.docxplease code in c#- please note that im a complete beginner-  northwind.docx
please code in c#- please note that im a complete beginner- northwind.docx
 
maincpp Build and procees a sorted linked list of Patie.pdf
maincpp   Build and procees a sorted linked list of Patie.pdfmaincpp   Build and procees a sorted linked list of Patie.pdf
maincpp Build and procees a sorted linked list of Patie.pdf
 
SQL -PHP Tutorial
SQL -PHP TutorialSQL -PHP Tutorial
SQL -PHP Tutorial
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdf
 
Cassandra Day London 2015: Getting Started with Apache Cassandra and Java
Cassandra Day London 2015: Getting Started with Apache Cassandra and JavaCassandra Day London 2015: Getting Started with Apache Cassandra and Java
Cassandra Day London 2015: Getting Started with Apache Cassandra and Java
 
Cassandra Day London: Building Java Applications
Cassandra Day London: Building Java ApplicationsCassandra Day London: Building Java Applications
Cassandra Day London: Building Java Applications
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
Intro to Parse
Intro to ParseIntro to Parse
Intro to Parse
 

More from ezhilvizhiyan

Hi please complete the following with detailed working out Find the .pdf
Hi please complete the following with detailed working out Find the .pdfHi please complete the following with detailed working out Find the .pdf
Hi please complete the following with detailed working out Find the .pdfezhilvizhiyan
 
Explain and discuss 4G wireless communications and their advantages..pdf
Explain and discuss 4G wireless communications and their advantages..pdfExplain and discuss 4G wireless communications and their advantages..pdf
Explain and discuss 4G wireless communications and their advantages..pdfezhilvizhiyan
 
Draw and describe a module of the cross-cultural communication pr.pdf
Draw and describe a module of the cross-cultural communication pr.pdfDraw and describe a module of the cross-cultural communication pr.pdf
Draw and describe a module of the cross-cultural communication pr.pdfezhilvizhiyan
 
Discuss the reasons why visions fail. What steps can be implemented .pdf
Discuss the reasons why visions fail. What steps can be implemented .pdfDiscuss the reasons why visions fail. What steps can be implemented .pdf
Discuss the reasons why visions fail. What steps can be implemented .pdfezhilvizhiyan
 
Describe the original purpose of the Clean Air Act Policy of 1963. E.pdf
Describe the original purpose of the Clean Air Act Policy of 1963. E.pdfDescribe the original purpose of the Clean Air Act Policy of 1963. E.pdf
Describe the original purpose of the Clean Air Act Policy of 1963. E.pdfezhilvizhiyan
 
Continuity 100 Let f be a continuous function on a metric space X. L.pdf
Continuity 100 Let f be a continuous function on a metric space X. L.pdfContinuity 100 Let f be a continuous function on a metric space X. L.pdf
Continuity 100 Let f be a continuous function on a metric space X. L.pdfezhilvizhiyan
 
Admitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdf
Admitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdfAdmitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdf
Admitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdfezhilvizhiyan
 
7. In many respects metal binding is similar to the binding of a prot.pdf
7. In many respects metal binding is similar to the binding of a prot.pdf7. In many respects metal binding is similar to the binding of a prot.pdf
7. In many respects metal binding is similar to the binding of a prot.pdfezhilvizhiyan
 
3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf
3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf
3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdfezhilvizhiyan
 
1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf
1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf
1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdfezhilvizhiyan
 
X Company has the following budgeted cash flows for JanuaryIf the .pdf
X Company has the following budgeted cash flows for JanuaryIf the .pdfX Company has the following budgeted cash flows for JanuaryIf the .pdf
X Company has the following budgeted cash flows for JanuaryIf the .pdfezhilvizhiyan
 
Why did animal phyla appear so suddenly during the Cambrian explosion.pdf
Why did animal phyla appear so suddenly during the Cambrian explosion.pdfWhy did animal phyla appear so suddenly during the Cambrian explosion.pdf
Why did animal phyla appear so suddenly during the Cambrian explosion.pdfezhilvizhiyan
 
Which of the following information-management systems uses artificia.pdf
Which of the following information-management systems uses artificia.pdfWhich of the following information-management systems uses artificia.pdf
Which of the following information-management systems uses artificia.pdfezhilvizhiyan
 
Which of the following was part of the reason for the European excha.pdf
Which of the following was part of the reason for the European excha.pdfWhich of the following was part of the reason for the European excha.pdf
Which of the following was part of the reason for the European excha.pdfezhilvizhiyan
 
Ture or false or uncertain ( explain why) Thank you! e. Output per c.pdf
Ture or false or uncertain ( explain why) Thank you! e. Output per c.pdfTure or false or uncertain ( explain why) Thank you! e. Output per c.pdf
Ture or false or uncertain ( explain why) Thank you! e. Output per c.pdfezhilvizhiyan
 
This is for a C programDene a Car structure type in your header le.pdf
This is for a C programDene a Car structure type in your header le.pdfThis is for a C programDene a Car structure type in your header le.pdf
This is for a C programDene a Car structure type in your header le.pdfezhilvizhiyan
 
The following code is based on the Josephus problem, the code does c.pdf
The following code is based on the Josephus problem, the code does c.pdfThe following code is based on the Josephus problem, the code does c.pdf
The following code is based on the Josephus problem, the code does c.pdfezhilvizhiyan
 
Tech transfers should the fed Gov’t keep subsidizing University .pdf
Tech transfers should the fed Gov’t keep subsidizing University .pdfTech transfers should the fed Gov’t keep subsidizing University .pdf
Tech transfers should the fed Gov’t keep subsidizing University .pdfezhilvizhiyan
 
Remaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdf
Remaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdfRemaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdf
Remaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdfezhilvizhiyan
 
QUESTION 9 Research on North American women serving as expatriates fo.pdf
QUESTION 9 Research on North American women serving as expatriates fo.pdfQUESTION 9 Research on North American women serving as expatriates fo.pdf
QUESTION 9 Research on North American women serving as expatriates fo.pdfezhilvizhiyan
 

More from ezhilvizhiyan (20)

Hi please complete the following with detailed working out Find the .pdf
Hi please complete the following with detailed working out Find the .pdfHi please complete the following with detailed working out Find the .pdf
Hi please complete the following with detailed working out Find the .pdf
 
Explain and discuss 4G wireless communications and their advantages..pdf
Explain and discuss 4G wireless communications and their advantages..pdfExplain and discuss 4G wireless communications and their advantages..pdf
Explain and discuss 4G wireless communications and their advantages..pdf
 
Draw and describe a module of the cross-cultural communication pr.pdf
Draw and describe a module of the cross-cultural communication pr.pdfDraw and describe a module of the cross-cultural communication pr.pdf
Draw and describe a module of the cross-cultural communication pr.pdf
 
Discuss the reasons why visions fail. What steps can be implemented .pdf
Discuss the reasons why visions fail. What steps can be implemented .pdfDiscuss the reasons why visions fail. What steps can be implemented .pdf
Discuss the reasons why visions fail. What steps can be implemented .pdf
 
Describe the original purpose of the Clean Air Act Policy of 1963. E.pdf
Describe the original purpose of the Clean Air Act Policy of 1963. E.pdfDescribe the original purpose of the Clean Air Act Policy of 1963. E.pdf
Describe the original purpose of the Clean Air Act Policy of 1963. E.pdf
 
Continuity 100 Let f be a continuous function on a metric space X. L.pdf
Continuity 100 Let f be a continuous function on a metric space X. L.pdfContinuity 100 Let f be a continuous function on a metric space X. L.pdf
Continuity 100 Let f be a continuous function on a metric space X. L.pdf
 
Admitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdf
Admitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdfAdmitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdf
Admitting New Partner With Bonus Cody Jenkins and Lacey Tanner formed.pdf
 
7. In many respects metal binding is similar to the binding of a prot.pdf
7. In many respects metal binding is similar to the binding of a prot.pdf7. In many respects metal binding is similar to the binding of a prot.pdf
7. In many respects metal binding is similar to the binding of a prot.pdf
 
3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf
3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf
3. Photosynthetic organisms produce about 300 x 1015 g of oxygen per .pdf
 
1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf
1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf
1. Which is less soluble in water, 1-pentanol or 1-heptanol Explain..pdf
 
X Company has the following budgeted cash flows for JanuaryIf the .pdf
X Company has the following budgeted cash flows for JanuaryIf the .pdfX Company has the following budgeted cash flows for JanuaryIf the .pdf
X Company has the following budgeted cash flows for JanuaryIf the .pdf
 
Why did animal phyla appear so suddenly during the Cambrian explosion.pdf
Why did animal phyla appear so suddenly during the Cambrian explosion.pdfWhy did animal phyla appear so suddenly during the Cambrian explosion.pdf
Why did animal phyla appear so suddenly during the Cambrian explosion.pdf
 
Which of the following information-management systems uses artificia.pdf
Which of the following information-management systems uses artificia.pdfWhich of the following information-management systems uses artificia.pdf
Which of the following information-management systems uses artificia.pdf
 
Which of the following was part of the reason for the European excha.pdf
Which of the following was part of the reason for the European excha.pdfWhich of the following was part of the reason for the European excha.pdf
Which of the following was part of the reason for the European excha.pdf
 
Ture or false or uncertain ( explain why) Thank you! e. Output per c.pdf
Ture or false or uncertain ( explain why) Thank you! e. Output per c.pdfTure or false or uncertain ( explain why) Thank you! e. Output per c.pdf
Ture or false or uncertain ( explain why) Thank you! e. Output per c.pdf
 
This is for a C programDene a Car structure type in your header le.pdf
This is for a C programDene a Car structure type in your header le.pdfThis is for a C programDene a Car structure type in your header le.pdf
This is for a C programDene a Car structure type in your header le.pdf
 
The following code is based on the Josephus problem, the code does c.pdf
The following code is based on the Josephus problem, the code does c.pdfThe following code is based on the Josephus problem, the code does c.pdf
The following code is based on the Josephus problem, the code does c.pdf
 
Tech transfers should the fed Gov’t keep subsidizing University .pdf
Tech transfers should the fed Gov’t keep subsidizing University .pdfTech transfers should the fed Gov’t keep subsidizing University .pdf
Tech transfers should the fed Gov’t keep subsidizing University .pdf
 
Remaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdf
Remaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdfRemaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdf
Remaining Time 31 minutes, 22 seconds QUESTION 1 Question Completion.pdf
 
QUESTION 9 Research on North American women serving as expatriates fo.pdf
QUESTION 9 Research on North American women serving as expatriates fo.pdfQUESTION 9 Research on North American women serving as expatriates fo.pdf
QUESTION 9 Research on North American women serving as expatriates fo.pdf
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

This project will implement a simple usernamepassword lookup system.pdf

  • 1. This project will implement a simple username/password lookup system using hash tables. You should create the Hash Table from scratch. It may be helpful to create a separate class called HashEntry, in which you can store a String username and String password. The Hash Table will store these entries using the username as the key and the password as the value. Create a hash code using the key to determine where the value is stored in the Hash Table. Here is a sample hash method. Feel free to borrow it for your program: privateint calcHashCode(String key) { int mod = key.hashCode() % size; return mod < 0 ? mod + size : mod; } You will be provided with a data file containing comma separated usernames and passwords. Read the data in from the file and put it into the table. Once the table is populated, ask the user to log into the system. If their username and password match the data in the table, alert the user that access has been granted: Login: trevor User trevor not found. Login: mary Password: test Authentication Failure Login: mary Password: contrary Authentication Successful Welcome mary Provided Data File (containing comma separated usernames and passwords): jack,broken.crown jill,tumblin'down mary,contrary bopeep,sheep!lost Solution //main.cpp #include #include #include
  • 2. #include #include #include "HashTable.cpp" using namespace std; /// the struct for the login and password struct Account { /// variables string login; string password; /// hash function static unsigned int hash(const string& str) { unsigned int val = 0; for (int i = 0; i < str.length(); ++i) { val += str[i]; } return val; } /// get key function string getKey() const { return login; } }; int main() { string loginI; string passwordI; string temp; /// open file ifstream fin ("password.dat"); fin.clear(); /// make new account to read into Account acct; /// make the hash table
  • 3. HashTable data (8); /// read in while (fin.good()) { fin >> acct.login >> acct.password; //cout << acct.login << " " << acct.password << endl; data.insert(acct); //data.showStructure(); } data.showStructure(); /// read in cout << "Login: "; cin >> loginI; do { cout << "Password: "; cin >> passwordI; /// check for login if (data.retrieve(loginI, acct)) { /// check if passwords are the same if ((acct.password == passwordI)) { /// same password, print success cout << "Authentication successful" << endl; } else { /// different password, print failure cout << "Authentication failure" << endl; } } else { /// if the data login is not saved print failure cout << "Authentication failure" << endl;
  • 4. } cout << "Login: "; cin >> loginI; } while(!cin.eof()); return 0; } ===================================================================== ===== #include #include #include #include #include "HashTable.h" #include "show10.cpp" using namespace std; template HashTable::HashTable(int initTableSize) { /// save size tableSize = initTableSize; /// initialize the array dataTable = new BSTree[tableSize]; } template HashTable::HashTable(const HashTable& other) { /// copy size and create new table tableSize = other.tableSize; dataTable = new BSTree[tableSize]; *this = other; } template
  • 5. HashTable& HashTable:: operator=(const HashTable& other) { /// if the same return if (this = &other) return *this; /// clear clear(); /// copy the size and create new table tableSize = other.tableSize; dataTable = new BSTree[tableSize]; /// go through tables and copy the trees for (int i = 0; i < tableSize; ++i) { dataTable[i] = other.dataTable[i]; } return *this; } template HashTable::~HashTable() { clear(); delete[] dataTable; } template void HashTable::insert(const DataType& newDataItem) { /// get hash int location = newDataItem.hash(newDataItem.getKey()) % tableSize; /// insert into tree dataTable[location].insert(newDataItem); } template bool HashTable:: remove(const KeyType& deleteKey) {
  • 6. /// get its location in the array int location = DataType::hash(deleteKey) % tableSize; /// check to delete it return dataTable[location].remove(deleteKey); } template bool HashTable:: retrieve(const KeyType& searchKey, DataType& returnItem) const { /// find location in the array int location = DataType::hash(searchKey) % tableSize; /// check if the item is there return dataTable[location].retrieve(searchKey, returnItem); } template void HashTable:: clear() { /// iterate through the complete hash table for (int i = 0; i < tableSize; ++i) { dataTable[i].clear(); } } /** * Not Used */ template bool HashTable:: isEmpty() const { bool flag = true; for (int i = 0; i < tableSize; ++i) { /// check to see if each tree insdie the table is empty flag = dataTable[i].isEmpty();
  • 7. /// if flag is ever turned into false, then return false if (flag == false) return false; } return true; } template double HashTable:: standardDeviation() const { } template void HashTable:: copyTable(const HashTable& source) { *this = source; } ================================================== // HashTable.h #ifndef HASHTABLE_H #define HASHTABLE_H #include #include using namespace std; #include "BSTree.cpp" template class HashTable { public: HashTable(int initTableSize); HashTable(const HashTable& other); HashTable& operator=(const HashTable& other); ~HashTable(); void insert(const DataType& newDataItem); bool remove(const KeyType& deleteKey); bool retrieve(const KeyType& searchKey, DataType& returnItem) const; void clear();
  • 8. bool isEmpty() const; void showStructure() const; double standardDeviation() const; private: void copyTable(const HashTable& source); int tableSize; BSTree* dataTable; }; #endif // ifndef HASHTABLE_H ==================================================================== //BSTree.cpp #include #include #include #include #include "BSTree.h" #include "show9.cpp" using namespace std; template < typename DataType, class KeyType > BSTree::BSTreeNode::BSTreeNode( const DataType& nodeDataItem, BSTreeNode *leftPtr, BSTreeNode *rightPtr ) : dataItem(nodeDataItem), left(leftPtr), right (rightPtr) { } template < typename DataType, class KeyType > BSTree::BSTree() { root = NULL; } template < typename DataType, class KeyType > BSTree::BSTree(const BSTree& source) { root=NULL;
  • 9. *this = source; } template < typename DataType, class KeyType > BSTree& BSTree::operator=(const BSTree& source) { if (this == &source) return *this; clear(); copyHelp(root, source.root); return *this; } template < typename DataType, class KeyType > void BSTree::copyHelp( BSTreeNode*& home, BSTreeNode* RHS ) { /// Stopping condition, end of tree if (RHS == NULL) { home = NULL; return; } /// Create node home = new BSTreeNode (RHS->dataItem, NULL, NULL); /// Recall with the other parts of the tree copyHelp(home->left, RHS->left); copyHelp(home->right, RHS->right); return; } template < typename DataType, class KeyType > BSTree::~BSTree () { clear(); } template < typename DataType, class KeyType > void BSTree::insert(const DataType& newDataItem)
  • 10. { insertHelper(root, newDataItem); } template < typename DataType, class KeyType > void BSTree::insertHelper(BSTreeNode* & location, const DataType& newDataItem) { /// if reached location, create the new node if (location==NULL) location = new BSTreeNode(newDataItem, NULL, NULL); /// if the current location is larger than data go left if (location->dataItem.getKey() > newDataItem.getKey()) insertHelper(location->left, newDataItem); /// if the current location is smaller than data, go right if (location->dataItem.getKey() < newDataItem.getKey()) insertHelper(location->right, newDataItem); } template < typename DataType, class KeyType > bool BSTree::retrieve(const KeyType& searchKey, DataType& searchDataItem) const { return retrieveHelper(root, searchKey, searchDataItem); } template < typename DataType, class KeyType > bool BSTree::retrieveHelper(BSTreeNode* location, const KeyType& searchKey, DataType& searchDataItem) const { /// if checked the complete tree, return false if (location == NULL) return false; /// if found, return true if (location->dataItem.getKey() == searchKey) { searchDataItem = location->dataItem; return true; } /// if what were are looking for is smaller go left else go right
  • 11. if (location->dataItem.getKey() > searchKey) { return retrieveHelper(location->left, searchKey, searchDataItem); } else { return retrieveHelper(location->right, searchKey, searchDataItem); } } template < typename DataType, class KeyType > bool BSTree:: remove ( const KeyType& deleteKey ) { return removeHelper(root, deleteKey); } template < typename DataType, class KeyType > bool BSTree:: removeHelper ( BSTreeNode* & location, const KeyType& deleteKey ) { /// if at the end and not found, return false if (location == NULL) return false; /// if found, delete if (location->dataItem.getKey() == deleteKey) { /// if no children if ((location->left == NULL) && (location->right == NULL)) { delete location; location = NULL; return true; } /// if one child /// left child, no right if ((location->left != NULL) && (location->right == NULL)) {
  • 12. BSTreeNode* temp; temp = location; location = location->left; delete temp; return true; } /// no left, right child if ((location->left == NULL) && (location->right != NULL)) { BSTreeNode* temp; temp = location; location = location->right; delete temp; return true; } /// if two children if ((location->left != NULL) && (location->right != NULL)) { BSTreeNode* temp; temp = location; /// get predecessor temp = temp->left; while (temp->right != NULL) temp = temp->right; /// overwrite the value to delete with the predecessor location->dataItem = temp->dataItem; /// delete the node with the value just written to the new location return removeHelper(location->left, temp->dataItem.getKey()); } } /// keep searching if (location->dataItem.getKey() > deleteKey) return removeHelper(location->left, deleteKey); else return removeHelper(location->right, deleteKey); }
  • 13. template < typename DataType, class KeyType > void BSTree:: writeKeys () const { writeKeysHelper(root); cout << endl; } template < typename DataType, class KeyType > void BSTree:: writeKeysHelper (BSTreeNode* location) const { if (!isEmpty()) { /// go all the way to the left if (location->left != NULL) { writeKeysHelper(location->left); } /// once all the way to the left print out the current cout << location->dataItem.getKey() << " "; /// check for the children to the right of the most left node if (location->right != NULL) { writeKeysHelper(location->right); } } } template < typename DataType, class KeyType > void BSTree:: clear() { clearHelper(root); root = NULL; } template < typename DataType, class KeyType > void BSTree:: clearHelper( BSTreeNode* & location ) { if(!isEmpty())
  • 14. { /// if there is more to the left recall with child if (location->left != NULL) clearHelper(location->left); /// if leftmost has a right child repeat process with the right child if (location->right != NULL) clearHelper(location->right); /// deallocate delete location; } } template < typename DataType, class KeyType > bool BSTree:: isEmpty () const { return (root == NULL); } template < typename DataType, class KeyType > int BSTree:: getHeight () const { if (isEmpty()) return 0; heightHelper(root); } template < typename DataType, class KeyType > int BSTree:: heightHelper ( BSTreeNode* location) const { /// if we reached a null spot, return 0 since nothing is added if (location == NULL) return 0; /// get the size of the left and right by recalling and going to the left and right int leftTree = heightHelper(location->left); int rightTree = heightHelper(location->right); /// return which ever is larger plus one since the current node is part of the height
  • 15. if (leftTree > rightTree) return leftTree+1; else return rightTree+1; } template < typename DataType, class KeyType > int BSTree:: getCount () const { return countHelper(root); } template < typename DataType, class KeyType > int BSTree:: countHelper (BSTreeNode* location) const { if (location == NULL) return 0; else return (countHelper(location->left)+countHelper(location->right)+1); } /** * NOT USED */ template < typename DataType, class KeyType > void BSTree:: writeLessThan ( const KeyType& searchKey ) const { } ================================================================== //BSTree.h #ifndef BSTREE_H #define BSTREE_H #include #include using namespace std; template < typename DataType, class KeyType > // DataType : tree data item
  • 16. class BSTree // KeyType : key field { public: // Constructor BSTree (); // Default constructor BSTree ( const BSTree& other ); // Copy constructor BSTree& operator= ( const BSTree& other ); // Overloaded assignment operator // Destructor ~BSTree (); // Binary search tree manipulation operations void insert ( const DataType& newDataItem ); // Insert data item bool retrieve ( const KeyType& searchKey, DataType& searchDataItem ) const; // Retrieve data item bool remove ( const KeyType& deleteKey ); // Remove data item void writeKeys () const; // Output keys void clear (); // Clear tree // Binary search tree status operations bool isEmpty () const; // Tree is empty // !! isFull() has been retired. Not very useful in a linked structure. // Output the tree structure -- used in testing/debugging void showStructure () const; // In-lab operations int getHeight () const; // Height of tree int getCount () const; // Number of nodes in tree void writeLessThan ( const KeyType& searchKey ) const; // Output keys < searchKey protected: class BSTreeNode // Inner class: facilitator for the BSTree class { public: // Constructor BSTreeNode ( const DataType &nodeDataItem, BSTreeNode *leftPtr, BSTreeNode *rightPtr ); // Data members DataType dataItem; // Binary search tree data item BSTreeNode *left, // Pointer to the left child
  • 17. *right; // Pointer to the right child }; // Recursive helpers for the public member functions -- insert // prototypes of these functions here. void showHelper ( BSTreeNode *p, int level ) const; void insertHelper(BSTreeNode* & location, const DataType& newDataItem); bool retrieveHelper(BSTreeNode* location, const KeyType& searchKey, DataType& searchDataItem) const; bool removeHelper ( BSTreeNode* & location, const KeyType& deleteKey ); void writeKeysHelper (BSTreeNode* location) const; void clearHelper( BSTreeNode* & location ); int heightHelper ( BSTreeNode* location) const; int countHelper (BSTreeNode* location) const; void copyHelp( BSTreeNode*& home, BSTreeNode* RHS ); // Data member BSTreeNode *root; // Pointer to the root node }; #endif // define BSTREE_H ===================================================================== = //show9.cpp template < typename DataType, typename KeyType > void BSTree:: showStructure () const { if ( root == 0 ) cout << "Empty tree" << endl; else { cout << endl; showHelper(root,1); cout << endl; } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template < typename DataType, typename KeyType >
  • 18. void BSTree:: showHelper ( BSTreeNode *p, int level ) const { int j; // Loop counter if ( p != 0 ) { showHelper(p->right,level+1); // Output right subtree for ( j = 0 ; j < level ; j++ ) // Tab over to level cout << "t"; cout << " " << p->dataItem.getKey(); // Output key if ( ( p->left != 0 ) && // Output "connector" ( p->right != 0 ) ) cout << "<"; else if ( p->right != 0 ) cout << "/"; else if ( p->left != 0 ) cout << ""; cout << endl; showHelper(p->left,level+1); // Output left subtree } } ======================================================