SlideShare a Scribd company logo
1 of 14
Download to read offline
Program 4
You are to write an efficient program that will read a dictionary of 100,000 words, and then
check a document of 2,000,000 words. The program should insert into an array the position of
each misspelled word. I have provided the driver program SpellRunner.cpp, and the necessary
class stubs in speller.h, and speller.cpp. You may add any classes and/or code you wish to
speller.cpp, and speller.h. You may also use, and alter any Weiss files. CreateDocs.out creates
files used for testing. Doc-3-4-1 and Dict-3-4-1 are two testing files for small file.
Problem: I need help in writing a code for my speller.cpp and speller.h that takes in a dictionary
array
and it stores it in a hash table (I am trying to use quadratic hash). After that I need to compare
each word with the words in the dictionary (probably using the find x function) and check if
there is a misspelled word.
If there are misspelled words, I have a array called int misspelled[] that would store the
misspelled words,
and have a counter called int *misspelledCount that would keep track of how many misspelled
words there are.
_____________________________________________________________________________
_________________
Speller.h
#ifndef SPELLER_H
#define SPELLER_H
#include "mynew.h"
#include "QuadraticProbing.h"
#include
class Speller
{
public:
QuadraticHashTable *hashDict;
Speller(char *dictionary[], int dictSize);
~Speller();
void check(char *document[], int docSize, int misspelled[], int *misspelledCount);
}; // class Speller
#endif
_____________________________________________________________________________
_________________
Speller.cpp
#include "speller.h"
Speller::Speller(char *dictionary[], int dictSize)
{
hashDict = new QuadraticHashTable (-1, dictSize);
for(int i = 0; i < dictSize; i++)
hashDict->insert(dictionary[i]);
} // Speller()
void Speller::check(char *document[], int docSize, int misspelled[],
int *misspelledCount)
{
*misspelledCount = 0;
//Check document array using dictionary that you stored in constructor
for(int i = 0; i < docSize; i++)
{
if(!(hashDict->find(document[i])))
{
++(*misspelledCount);
misspelled[i] = 1;
}
else
{
misspelled[i] = 0;
}
}
//Store the array index of the misspelled word in the corresponding array and increments the
count of misspelled words
} // check()
Speller::~Speller()
{
} // ~Speller()
_____________________________________________________________________________
____________
SpellRunner.cpp
#include
#include
#include
#include
#include
#include "CPUTimer.h"
#include "mynew.h"
#include "speller.h"
// uncomment line below for DOS/Windows OS.
// #define DOS
#ifdef DOS
#include
#else
#include
#endif
extern int maxRAM;
extern int currentRAM;
using namespace std;
char* readDictionary(char *filename, char **dictionary, int dictSize)
{
int fileSize;
char *s;
struct stat statbuf;
stat(filename, &statbuf);
fileSize = statbuf.st_size;
s = new char[fileSize + 1];
ifstream inf(filename);
inf.read(s, fileSize);
inf.close();
s[fileSize] = '0';
dictionary[0] = strtok(s, " ");
for(int i = 1; i < dictSize; i++)
dictionary[i] = strtok(NULL, "  ");
return s;
} // readDictionary
char* readDocument(char **document, int dictSize, int docSize, int seed)
{
char *s, filename[80];
int fileSize;
struct stat statbuf;
sprintf(filename, "Doc-%d-%d-%d.txt", dictSize, docSize, seed);
stat(filename, &statbuf);
fileSize = statbuf.st_size;
s = new char[fileSize + 100];
ifstream inf(filename);
inf.read(s, fileSize);
inf.close();
s[fileSize] = '0';
document[0] = strtok(s, " ");
for(int i = 1; i < docSize; i++)
document[i] = strtok(NULL, "  ");
return s;
} // readDocument()
void readWrongs(int *wrongs, int dictSize, int docSize, int seed,
int &wrongCount)
{
char filename[80];
wrongCount = 0;
sprintf(filename, "Wrongs-%d-%d-%d.txt", dictSize, docSize, seed);
ifstream inf(filename);
while(inf >> wrongs[wrongCount++]);
wrongCount--;
} // readWrongs()
void checkAnswers(int wrongs[], int wrongCount, int misspelled[],
int misspelledCount)
{
for(int i = 0; i < wrongCount && i < misspelledCount; i++)
if(wrongs[i] < misspelled[i])
{
cout << "Speller missed misspelled word # " << wrongs[i] << endl;
return;
}
else
if(wrongs[i] > misspelled[i])
{
cout << "Speller thought correctly spelled word # " << misspelled[i]
<< " was wrong ";
return;
}
if(wrongCount != misspelledCount)
cout << "Speller found " << misspelledCount << " misspelled words when "
<< " there were really " << wrongCount << " misspelled words. ";
} // checkAnswers
void cleanup(char **dictionary, char *docFilePtr, char **document, int *wrongs, int
*misspelled)
{
delete [] dictionary;
delete [] docFilePtr;
delete [] document;
delete [] wrongs;
delete [] misspelled;
} // cleanup()
int main(int argc, char* argv[])
{
char line[80], **dictionary, **document, *dictFilePtr, *docFilePtr;
int *wrongs, *misspelled, misspelledCount = 0, seed, dictSize, docSize,
wrongCount, tempMaxRAM, tempCurrentRAM;
strcpy(line, argv[1]);
strtok(line, "-");
dictSize = atoi(strtok(NULL, "-"));
docSize = atoi(strtok(NULL, "-"));
seed = atoi(strtok(NULL, "."));
dictionary = new char*[dictSize + 3];
dictFilePtr = readDictionary(argv[1], dictionary, dictSize);
document = new char*[docSize + 3];
docFilePtr = readDocument(document, dictSize, docSize, seed);
wrongs = new int[docSize];
readWrongs(wrongs, dictSize, docSize, seed, wrongCount);
misspelled = new int[docSize];
CPUTimer ct;
maxRAM = currentRAM = 0;
Speller *speller = new Speller(dictionary, dictSize);
tempMaxRAM = maxRAM;
tempCurrentRAM = currentRAM;
delete [] dictFilePtr;
maxRAM = tempMaxRAM;
currentRAM = tempCurrentRAM;
speller->check(document, docSize, misspelled, &misspelledCount);
cout << "CPU Time: " << ct.cur_CPUTime() << " Real RAM: " << maxRAM << endl;
checkAnswers(wrongs, wrongCount, misspelled, misspelledCount);
cleanup(dictionary, docFilePtr, document, wrongs, misspelled);
delete speller;
return 0;
} // main()
_____________________________________________________________________________
_________________
QuadraticProbing.cpp
#include "QuadraticProbing.h"
/**
* Internal method to test if a positive number is prime.
* Not an efficient algorithm.
*/
template
bool QuadraticHashTable::isPrime( int n ) const
{
if( n == 2 || n == 3 )
return true;
if( n == 1 || n % 2 == 0 )
return false;
for( int i = 3; i * i <= n; i += 2 )
if( n % i == 0 )
return false;
return true;
}
/**
* Internal method to return a prime number at least as large as n.
* Assumes n > 0.
*/
template
int QuadraticHashTable::nextPrime( int n ) const
{
if( n % 2 == 0 )
n++;
for( ; !isPrime( n ); n += 2 )
;
return n;
}
/**
* Construct the hash table.
*/
template
QuadraticHashTable::QuadraticHashTable( const HashedObj & notFound, int size )
: array( nextPrime( size ) ), ITEM_NOT_FOUND( notFound )
{
makeEmpty( );
}
/**
* Insert item x into the hash table. If the item is
* already present, then do nothing.
*/
template
void QuadraticHashTable::insert( const HashedObj & x )
{
// Insert x as active
int currentPos = findPos( x );
if( isActive( currentPos ) )
return;
array[ currentPos ] = HashEntry( x, ACTIVE );
// Rehash; see Section 5.5
if( ++currentSize > array.size( ) / 2 )
rehash( );
}
/**
* Expand the hash table.
*/
template
void QuadraticHashTable::rehash( )
{
vector oldArray = array;
// Create new double-sized, empty table
array.resize( nextPrime( 2 * oldArray.size( ) ) );
for( int j = 0; j < array.size( ); j++ )
array[ j ].info = EMPTY;
// Copy table over
currentSize = 0;
for( int i = 0; i < oldArray.size( ); i++ )
if( oldArray[ i ].info == ACTIVE )
insert( oldArray[ i ].element );
}
/**
* Method that performs quadratic probing resolution.
* Return the position where the search for x terminates.
*/
template
int QuadraticHashTable::findPos( const HashedObj & x ) const
{
/* 1*/ int collisionNum = 0;
/* 2*/ int currentPos = hash( x, array.size( ) );
/* 3*/ while( array[ currentPos ].info != EMPTY &&
array[ currentPos ].element != x )
{
/* 4*/ currentPos += 2 * ++collisionNum - 1; // Compute ith probe
/* 5*/ if( currentPos >= array.size( ) )
/* 6*/ currentPos -= array.size( );
}
/* 7*/ return currentPos;
}
/**
* Remove item x from the hash table.
*/
template
void QuadraticHashTable::remove( const HashedObj & x )
{
int currentPos = findPos( x );
if( isActive( currentPos ) )
array[ currentPos ].info = DELETED;
}
/**
* Find item x in the hash table.
* Return the matching item, or ITEM_NOT_FOUND, if not found.
*/
template
const HashedObj & QuadraticHashTable::find( const HashedObj & x ) const
{
int currentPos = findPos( x );
return isActive( currentPos ) ? array[ currentPos ].element : ITEM_NOT_FOUND;
// Above mentions only if active, if it is return array element, else return not found
}
/**
* Make the hash table logically empty.
*/
template
void QuadraticHashTable::makeEmpty( )
{
currentSize = 0;
for( int i = 0; i < array.size( ); i++ )
array[ i ].info = EMPTY;
}
/**
* Deep copy.
*/
template
const QuadraticHashTable & QuadraticHashTable::
operator=( const QuadraticHashTable & rhs )
{
if( this != &rhs )
{
array = rhs.array;
currentSize = rhs.currentSize;
}
return *this;
}
/**
* Return true if currentPos exists and is active.
*/
template
bool QuadraticHashTable::isActive( int currentPos ) const
{
return array[ currentPos ].info == ACTIVE;
}
/**
* A hash routine for string objects.
*/
template
int QuadraticHashTable::hash( const string & key, int tableSize ) const
{
int hashVal = 0;
for( int i = 0; i < key.length( ); i++ )
hashVal = 37 * hashVal + key[ i ];
hashVal %= tableSize;
if( hashVal < 0 )
hashVal += tableSize;
return hashVal;
}
/**
* A hash routine for ints.
*/
template
int QuadraticHashTable::hash( int key, int tableSize ) const
{
if( key < 0 ) key = -key;
return key % tableSize;
}
_____________________________________________________________________________
____________
QuadraticProbing.h
#ifndef _QUADRATIC_PROBING_H_
#define _QUADRATIC_PROBING_H_
#include "vector.h"
#include "mystring.h"
// QuadraticProbing Hash table class
//
// CONSTRUCTION: an initialization for ITEM_NOT_FOUND
// and an approximate initial size or default of 101
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x
// Hashable find( x ) --> Return item that matches x
// void makeEmpty( ) --> Remove all items
// int hash( String str, int tableSize )
// --> Static method to hash strings
class QuadraticHashTable
{
public:
explicit QuadraticHashTable( const HashedObj & notFound, int size = 101 );
QuadraticHashTable( const QuadraticHashTable & rhs )
: ITEM_NOT_FOUND( rhs.ITEM_NOT_FOUND ),
array( rhs.array ), currentSize( rhs.currentSize ) { }
const HashedObj & find( const HashedObj & x ) const;
void makeEmpty( );
void insert( const HashedObj & x );
void remove( const HashedObj & x );
const QuadraticHashTable & operator=( const QuadraticHashTable & rhs );
enum EntryType { ACTIVE, EMPTY, DELETED };
private:
struct HashEntry
{
HashedObj element;
EntryType info;
HashEntry( const HashedObj & e = HashedObj( ), EntryType i = EMPTY )
: element( e ), info( i ) { }
};
vector array;
int currentSize;
const HashedObj ITEM_NOT_FOUND;
bool isPrime( int n ) const;
int nextPrime( int n ) const;
bool isActive( int currentPos ) const;
char* findPos( const HashedObj & x ) const;
char* hash( const string & key, int tableSize ) const;
int hash( int key, int tableSize ) const;
void rehash( );
};
#include "QuadraticProbing.cpp"
#endif
_____________________________________________________________________________
____________
Dict-3-4-1.txt (Dictionary)
luov
vwucoxynjm
lsrwwvov
_____________________________________________________________________________
____________
Doc-3-4-1.txt (Checking for misspell words)
lsrwwvov
vwuboxynjm
luov
vwucoxynj
Solution
int main(int argc, char* argv[])
{
char line[80], **dictionary, **document, *dictFilePtr, *docFilePtr;
int *wrongs, *misspelled, misspelledCount = 0, seed, dictSize, docSize,
wrongCount, tempMaxRAM, tempCurrentRAM;
strcpy(line, argv[1]);
strtok(line, "-");
dictSize = atoi(strtok(NULL, "-"));
docSize = atoi(strtok(NULL, "-"));
seed = atoi(strtok(NULL, "."));
dictionary = new char*[dictSize + 3];
dictFilePtr = readDictionary(argv[1], dictionary, dictSize);
document = new char*[docSize + 3];
docFilePtr = readDocument(document, dictSize, docSize, seed);
wrongs = new int[docSize];
readWrongs(wrongs, dictSize, docSize, seed, wrongCount);
misspelled = new int[docSize];
CPUTimer ct;
maxRAM = currentRAM = 0;
Speller *speller = new Speller(dictionary, dictSize);
tempMaxRAM = maxRAM;
tempCurrentRAM = currentRAM;
delete [] dictFilePtr;
maxRAM = tempMaxRAM;
currentRAM = tempCurrentRAM;
speller->check(document, docSize, misspelled, &misspelledCount);
cout << "CPU Time: " << ct.cur_CPUTime() << " Real RAM: " << maxRAM << endl;
checkAnswers(wrongs, wrongCount, misspelled, misspelledCount);
cleanup(dictionary, docFilePtr, document, wrongs, misspelled);
delete speller;
return 0;
} // main()ZZ
[ssdavis@lect1 p4]$ CreateDocs.out
Dictionary size: 3
Document size: 4
Seed: 1
[ssdavis@lect1 p4]$ cat Dict-3-4-1.txt
luov
vwucoxynjm
lsrwwvov
[ssdavis@lect1 p4]
[ssdavis@lect1 p4]$ cat Doc-3-4-1.txt
lsrwwvov
vwuboxynjm
luov
vwucoxynjm
[ssdavis@lect1 p4]
[ssdavis@lect1 p4]$ cat Wrongs-3-4-1.txt
1
[ssdavis@lect1 p4]$
[ssdavis@lect1 p4]$ speller.out Dict-100000-2000000-7.txt
CPU Time: 0.170697 Real RAM: 1230872
[ssdavis@lect1 p4]$

More Related Content

Similar to Program 4You are to write an efficient program that will read a di.pdf

Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfrajkumarm401
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdfrahulfancycorner21
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfjillisacebi75827
 
This is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdfThis is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdfinfo334223
 
Php7 hashtable
Php7 hashtablePhp7 hashtable
Php7 hashtable桐 王
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbaivibrantuser
 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdffantoosh1
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxDIPESH30
 
Please answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docxPlease answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docxcgraciela1
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdffantoosh1
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#Shahzad
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...DEEPANSHU GUPTA
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDBantoinegirbal
 

Similar to Program 4You are to write an efficient program that will read a di.pdf (20)

lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Write a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdfWrite a C++ program 1. Study the function process_text() in file.pdf
Write a C++ program 1. Study the function process_text() in file.pdf
 
This is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdfThis is the main file include itemh include itemList.pdf
This is the main file include itemh include itemList.pdf
 
Php7 hashtable
Php7 hashtablePhp7 hashtable
Php7 hashtable
 
Pointer
PointerPointer
Pointer
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Js types
Js typesJs types
Js types
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdf
 
Hash table (2)
Hash table (2)Hash table (2)
Hash table (2)
 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
 
Please answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docxPlease answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docx
 
I need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdfI need help with this code working Create another project and add yo.pdf
I need help with this code working Create another project and add yo.pdf
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...APPLICATION TO DOCUMENT ALL THE  DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
APPLICATION TO DOCUMENT ALL THE DETAILS OF JAVA CLASSES OF A PROJECT AT ONCE...
 
2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB2011 Mongo FR - Indexing in MongoDB
2011 Mongo FR - Indexing in MongoDB
 

More from ezzi552

Execute the following code and identify the errors in the program. D.pdf
Execute the following code and identify the errors in the program. D.pdfExecute the following code and identify the errors in the program. D.pdf
Execute the following code and identify the errors in the program. D.pdfezzi552
 
Essay question The genomes of lots and lots of organisms (mostly ba.pdf
Essay question The genomes of lots and lots of organisms (mostly ba.pdfEssay question The genomes of lots and lots of organisms (mostly ba.pdf
Essay question The genomes of lots and lots of organisms (mostly ba.pdfezzi552
 
Consider the language L = { anb2n n 0 }.Give an implementation.pdf
Consider the language L = { anb2n  n  0 }.Give an implementation.pdfConsider the language L = { anb2n  n  0 }.Give an implementation.pdf
Consider the language L = { anb2n n 0 }.Give an implementation.pdfezzi552
 
Case Study.You are the Chair of the Department of Surgery at a lar.pdf
Case Study.You are the Chair of the Department of Surgery at a lar.pdfCase Study.You are the Chair of the Department of Surgery at a lar.pdf
Case Study.You are the Chair of the Department of Surgery at a lar.pdfezzi552
 
An Unsorted Type ADT is to be extended by the addition of function S.pdf
An Unsorted Type ADT is to be extended by the addition of function S.pdfAn Unsorted Type ADT is to be extended by the addition of function S.pdf
An Unsorted Type ADT is to be extended by the addition of function S.pdfezzi552
 
alue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdf
alue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdfalue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdf
alue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdfezzi552
 
1)Using general mass-media (such as news sites) identify a recent co.pdf
1)Using general mass-media (such as news sites) identify a recent co.pdf1)Using general mass-media (such as news sites) identify a recent co.pdf
1)Using general mass-media (such as news sites) identify a recent co.pdfezzi552
 
1. The notion that two network exist in the brain, one for emotional.pdf
1. The notion that two network exist in the brain, one for emotional.pdf1. The notion that two network exist in the brain, one for emotional.pdf
1. The notion that two network exist in the brain, one for emotional.pdfezzi552
 
Which of the following is a bank liabilityA. Reserve deposits at .pdf
Which of the following is a bank liabilityA. Reserve deposits at .pdfWhich of the following is a bank liabilityA. Reserve deposits at .pdf
Which of the following is a bank liabilityA. Reserve deposits at .pdfezzi552
 
What was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdf
What was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdfWhat was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdf
What was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdfezzi552
 
What does the following program do What’s its time complexity Just.pdf
What does the following program do What’s its time complexity Just.pdfWhat does the following program do What’s its time complexity Just.pdf
What does the following program do What’s its time complexity Just.pdfezzi552
 
What is not true about the membranes of prokaryotic organism a. The.pdf
What is not true about the membranes of prokaryotic organism  a. The.pdfWhat is not true about the membranes of prokaryotic organism  a. The.pdf
What is not true about the membranes of prokaryotic organism a. The.pdfezzi552
 
What behavior characteristics are associated with each of the four s.pdf
What behavior characteristics are associated with each of the four s.pdfWhat behavior characteristics are associated with each of the four s.pdf
What behavior characteristics are associated with each of the four s.pdfezzi552
 
What are someways to better understand accounting There is a lot of.pdf
What are someways to better understand accounting There is a lot of.pdfWhat are someways to better understand accounting There is a lot of.pdf
What are someways to better understand accounting There is a lot of.pdfezzi552
 
Based on the elements from the Ruby Payne readings create a resource.pdf
Based on the elements from the Ruby Payne readings create a resource.pdfBased on the elements from the Ruby Payne readings create a resource.pdf
Based on the elements from the Ruby Payne readings create a resource.pdfezzi552
 
The answer has to be original.For this week’s discussion, complete.pdf
The answer has to be original.For this week’s discussion, complete.pdfThe answer has to be original.For this week’s discussion, complete.pdf
The answer has to be original.For this week’s discussion, complete.pdfezzi552
 
Assume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdfAssume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdfezzi552
 
6. Establishing priorities is an issue that local governments strugg.pdf
6. Establishing priorities is an issue that local governments strugg.pdf6. Establishing priorities is an issue that local governments strugg.pdf
6. Establishing priorities is an issue that local governments strugg.pdfezzi552
 
Suppose that A and B are attributes of a certain relational table. G.pdf
Suppose that A and B are attributes of a certain relational table. G.pdfSuppose that A and B are attributes of a certain relational table. G.pdf
Suppose that A and B are attributes of a certain relational table. G.pdfezzi552
 
RHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdf
RHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdfRHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdf
RHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdfezzi552
 

More from ezzi552 (20)

Execute the following code and identify the errors in the program. D.pdf
Execute the following code and identify the errors in the program. D.pdfExecute the following code and identify the errors in the program. D.pdf
Execute the following code and identify the errors in the program. D.pdf
 
Essay question The genomes of lots and lots of organisms (mostly ba.pdf
Essay question The genomes of lots and lots of organisms (mostly ba.pdfEssay question The genomes of lots and lots of organisms (mostly ba.pdf
Essay question The genomes of lots and lots of organisms (mostly ba.pdf
 
Consider the language L = { anb2n n 0 }.Give an implementation.pdf
Consider the language L = { anb2n  n  0 }.Give an implementation.pdfConsider the language L = { anb2n  n  0 }.Give an implementation.pdf
Consider the language L = { anb2n n 0 }.Give an implementation.pdf
 
Case Study.You are the Chair of the Department of Surgery at a lar.pdf
Case Study.You are the Chair of the Department of Surgery at a lar.pdfCase Study.You are the Chair of the Department of Surgery at a lar.pdf
Case Study.You are the Chair of the Department of Surgery at a lar.pdf
 
An Unsorted Type ADT is to be extended by the addition of function S.pdf
An Unsorted Type ADT is to be extended by the addition of function S.pdfAn Unsorted Type ADT is to be extended by the addition of function S.pdf
An Unsorted Type ADT is to be extended by the addition of function S.pdf
 
alue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdf
alue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdfalue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdf
alue 0.83 points M7-6 Calculating Cost of Goods Available for Sale, E.pdf
 
1)Using general mass-media (such as news sites) identify a recent co.pdf
1)Using general mass-media (such as news sites) identify a recent co.pdf1)Using general mass-media (such as news sites) identify a recent co.pdf
1)Using general mass-media (such as news sites) identify a recent co.pdf
 
1. The notion that two network exist in the brain, one for emotional.pdf
1. The notion that two network exist in the brain, one for emotional.pdf1. The notion that two network exist in the brain, one for emotional.pdf
1. The notion that two network exist in the brain, one for emotional.pdf
 
Which of the following is a bank liabilityA. Reserve deposits at .pdf
Which of the following is a bank liabilityA. Reserve deposits at .pdfWhich of the following is a bank liabilityA. Reserve deposits at .pdf
Which of the following is a bank liabilityA. Reserve deposits at .pdf
 
What was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdf
What was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdfWhat was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdf
What was Eisenhower’s reinsurance plan What was Eisenhower’s r.pdf
 
What does the following program do What’s its time complexity Just.pdf
What does the following program do What’s its time complexity Just.pdfWhat does the following program do What’s its time complexity Just.pdf
What does the following program do What’s its time complexity Just.pdf
 
What is not true about the membranes of prokaryotic organism a. The.pdf
What is not true about the membranes of prokaryotic organism  a. The.pdfWhat is not true about the membranes of prokaryotic organism  a. The.pdf
What is not true about the membranes of prokaryotic organism a. The.pdf
 
What behavior characteristics are associated with each of the four s.pdf
What behavior characteristics are associated with each of the four s.pdfWhat behavior characteristics are associated with each of the four s.pdf
What behavior characteristics are associated with each of the four s.pdf
 
What are someways to better understand accounting There is a lot of.pdf
What are someways to better understand accounting There is a lot of.pdfWhat are someways to better understand accounting There is a lot of.pdf
What are someways to better understand accounting There is a lot of.pdf
 
Based on the elements from the Ruby Payne readings create a resource.pdf
Based on the elements from the Ruby Payne readings create a resource.pdfBased on the elements from the Ruby Payne readings create a resource.pdf
Based on the elements from the Ruby Payne readings create a resource.pdf
 
The answer has to be original.For this week’s discussion, complete.pdf
The answer has to be original.For this week’s discussion, complete.pdfThe answer has to be original.For this week’s discussion, complete.pdf
The answer has to be original.For this week’s discussion, complete.pdf
 
Assume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdfAssume you have a scanner object (called input).Declare an integer.pdf
Assume you have a scanner object (called input).Declare an integer.pdf
 
6. Establishing priorities is an issue that local governments strugg.pdf
6. Establishing priorities is an issue that local governments strugg.pdf6. Establishing priorities is an issue that local governments strugg.pdf
6. Establishing priorities is an issue that local governments strugg.pdf
 
Suppose that A and B are attributes of a certain relational table. G.pdf
Suppose that A and B are attributes of a certain relational table. G.pdfSuppose that A and B are attributes of a certain relational table. G.pdf
Suppose that A and B are attributes of a certain relational table. G.pdf
 
RHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdf
RHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdfRHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdf
RHCE is least associated with which Rh group (D--, R1r, Ror, Rzy) .pdf
 

Recently uploaded

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
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

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
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

Program 4You are to write an efficient program that will read a di.pdf

  • 1. Program 4 You are to write an efficient program that will read a dictionary of 100,000 words, and then check a document of 2,000,000 words. The program should insert into an array the position of each misspelled word. I have provided the driver program SpellRunner.cpp, and the necessary class stubs in speller.h, and speller.cpp. You may add any classes and/or code you wish to speller.cpp, and speller.h. You may also use, and alter any Weiss files. CreateDocs.out creates files used for testing. Doc-3-4-1 and Dict-3-4-1 are two testing files for small file. Problem: I need help in writing a code for my speller.cpp and speller.h that takes in a dictionary array and it stores it in a hash table (I am trying to use quadratic hash). After that I need to compare each word with the words in the dictionary (probably using the find x function) and check if there is a misspelled word. If there are misspelled words, I have a array called int misspelled[] that would store the misspelled words, and have a counter called int *misspelledCount that would keep track of how many misspelled words there are. _____________________________________________________________________________ _________________ Speller.h #ifndef SPELLER_H #define SPELLER_H #include "mynew.h" #include "QuadraticProbing.h" #include class Speller { public: QuadraticHashTable *hashDict; Speller(char *dictionary[], int dictSize); ~Speller(); void check(char *document[], int docSize, int misspelled[], int *misspelledCount); }; // class Speller #endif _____________________________________________________________________________ _________________
  • 2. Speller.cpp #include "speller.h" Speller::Speller(char *dictionary[], int dictSize) { hashDict = new QuadraticHashTable (-1, dictSize); for(int i = 0; i < dictSize; i++) hashDict->insert(dictionary[i]); } // Speller() void Speller::check(char *document[], int docSize, int misspelled[], int *misspelledCount) { *misspelledCount = 0; //Check document array using dictionary that you stored in constructor for(int i = 0; i < docSize; i++) { if(!(hashDict->find(document[i]))) { ++(*misspelledCount); misspelled[i] = 1; } else { misspelled[i] = 0; } } //Store the array index of the misspelled word in the corresponding array and increments the count of misspelled words } // check() Speller::~Speller() { } // ~Speller() _____________________________________________________________________________ ____________ SpellRunner.cpp #include #include
  • 3. #include #include #include #include "CPUTimer.h" #include "mynew.h" #include "speller.h" // uncomment line below for DOS/Windows OS. // #define DOS #ifdef DOS #include #else #include #endif extern int maxRAM; extern int currentRAM; using namespace std; char* readDictionary(char *filename, char **dictionary, int dictSize) { int fileSize; char *s; struct stat statbuf; stat(filename, &statbuf); fileSize = statbuf.st_size; s = new char[fileSize + 1]; ifstream inf(filename); inf.read(s, fileSize); inf.close(); s[fileSize] = '0'; dictionary[0] = strtok(s, " "); for(int i = 1; i < dictSize; i++) dictionary[i] = strtok(NULL, " "); return s; } // readDictionary char* readDocument(char **document, int dictSize, int docSize, int seed) { char *s, filename[80];
  • 4. int fileSize; struct stat statbuf; sprintf(filename, "Doc-%d-%d-%d.txt", dictSize, docSize, seed); stat(filename, &statbuf); fileSize = statbuf.st_size; s = new char[fileSize + 100]; ifstream inf(filename); inf.read(s, fileSize); inf.close(); s[fileSize] = '0'; document[0] = strtok(s, " "); for(int i = 1; i < docSize; i++) document[i] = strtok(NULL, " "); return s; } // readDocument() void readWrongs(int *wrongs, int dictSize, int docSize, int seed, int &wrongCount) { char filename[80]; wrongCount = 0; sprintf(filename, "Wrongs-%d-%d-%d.txt", dictSize, docSize, seed); ifstream inf(filename); while(inf >> wrongs[wrongCount++]); wrongCount--; } // readWrongs() void checkAnswers(int wrongs[], int wrongCount, int misspelled[], int misspelledCount) { for(int i = 0; i < wrongCount && i < misspelledCount; i++) if(wrongs[i] < misspelled[i]) { cout << "Speller missed misspelled word # " << wrongs[i] << endl; return; } else if(wrongs[i] > misspelled[i])
  • 5. { cout << "Speller thought correctly spelled word # " << misspelled[i] << " was wrong "; return; } if(wrongCount != misspelledCount) cout << "Speller found " << misspelledCount << " misspelled words when " << " there were really " << wrongCount << " misspelled words. "; } // checkAnswers void cleanup(char **dictionary, char *docFilePtr, char **document, int *wrongs, int *misspelled) { delete [] dictionary; delete [] docFilePtr; delete [] document; delete [] wrongs; delete [] misspelled; } // cleanup() int main(int argc, char* argv[]) { char line[80], **dictionary, **document, *dictFilePtr, *docFilePtr; int *wrongs, *misspelled, misspelledCount = 0, seed, dictSize, docSize, wrongCount, tempMaxRAM, tempCurrentRAM; strcpy(line, argv[1]); strtok(line, "-"); dictSize = atoi(strtok(NULL, "-")); docSize = atoi(strtok(NULL, "-")); seed = atoi(strtok(NULL, ".")); dictionary = new char*[dictSize + 3]; dictFilePtr = readDictionary(argv[1], dictionary, dictSize); document = new char*[docSize + 3]; docFilePtr = readDocument(document, dictSize, docSize, seed); wrongs = new int[docSize]; readWrongs(wrongs, dictSize, docSize, seed, wrongCount);
  • 6. misspelled = new int[docSize]; CPUTimer ct; maxRAM = currentRAM = 0; Speller *speller = new Speller(dictionary, dictSize); tempMaxRAM = maxRAM; tempCurrentRAM = currentRAM; delete [] dictFilePtr; maxRAM = tempMaxRAM; currentRAM = tempCurrentRAM; speller->check(document, docSize, misspelled, &misspelledCount); cout << "CPU Time: " << ct.cur_CPUTime() << " Real RAM: " << maxRAM << endl; checkAnswers(wrongs, wrongCount, misspelled, misspelledCount); cleanup(dictionary, docFilePtr, document, wrongs, misspelled); delete speller; return 0; } // main() _____________________________________________________________________________ _________________ QuadraticProbing.cpp #include "QuadraticProbing.h" /** * Internal method to test if a positive number is prime. * Not an efficient algorithm. */ template bool QuadraticHashTable::isPrime( int n ) const { if( n == 2 || n == 3 ) return true; if( n == 1 || n % 2 == 0 ) return false; for( int i = 3; i * i <= n; i += 2 ) if( n % i == 0 ) return false;
  • 7. return true; } /** * Internal method to return a prime number at least as large as n. * Assumes n > 0. */ template int QuadraticHashTable::nextPrime( int n ) const { if( n % 2 == 0 ) n++; for( ; !isPrime( n ); n += 2 ) ; return n; } /** * Construct the hash table. */ template QuadraticHashTable::QuadraticHashTable( const HashedObj & notFound, int size ) : array( nextPrime( size ) ), ITEM_NOT_FOUND( notFound ) { makeEmpty( ); } /** * Insert item x into the hash table. If the item is * already present, then do nothing. */ template void QuadraticHashTable::insert( const HashedObj & x ) { // Insert x as active int currentPos = findPos( x ); if( isActive( currentPos ) ) return; array[ currentPos ] = HashEntry( x, ACTIVE );
  • 8. // Rehash; see Section 5.5 if( ++currentSize > array.size( ) / 2 ) rehash( ); } /** * Expand the hash table. */ template void QuadraticHashTable::rehash( ) { vector oldArray = array; // Create new double-sized, empty table array.resize( nextPrime( 2 * oldArray.size( ) ) ); for( int j = 0; j < array.size( ); j++ ) array[ j ].info = EMPTY; // Copy table over currentSize = 0; for( int i = 0; i < oldArray.size( ); i++ ) if( oldArray[ i ].info == ACTIVE ) insert( oldArray[ i ].element ); } /** * Method that performs quadratic probing resolution. * Return the position where the search for x terminates. */ template int QuadraticHashTable::findPos( const HashedObj & x ) const { /* 1*/ int collisionNum = 0; /* 2*/ int currentPos = hash( x, array.size( ) ); /* 3*/ while( array[ currentPos ].info != EMPTY && array[ currentPos ].element != x ) { /* 4*/ currentPos += 2 * ++collisionNum - 1; // Compute ith probe /* 5*/ if( currentPos >= array.size( ) ) /* 6*/ currentPos -= array.size( );
  • 9. } /* 7*/ return currentPos; } /** * Remove item x from the hash table. */ template void QuadraticHashTable::remove( const HashedObj & x ) { int currentPos = findPos( x ); if( isActive( currentPos ) ) array[ currentPos ].info = DELETED; } /** * Find item x in the hash table. * Return the matching item, or ITEM_NOT_FOUND, if not found. */ template const HashedObj & QuadraticHashTable::find( const HashedObj & x ) const { int currentPos = findPos( x ); return isActive( currentPos ) ? array[ currentPos ].element : ITEM_NOT_FOUND; // Above mentions only if active, if it is return array element, else return not found } /** * Make the hash table logically empty. */ template void QuadraticHashTable::makeEmpty( ) { currentSize = 0; for( int i = 0; i < array.size( ); i++ ) array[ i ].info = EMPTY; } /**
  • 10. * Deep copy. */ template const QuadraticHashTable & QuadraticHashTable:: operator=( const QuadraticHashTable & rhs ) { if( this != &rhs ) { array = rhs.array; currentSize = rhs.currentSize; } return *this; } /** * Return true if currentPos exists and is active. */ template bool QuadraticHashTable::isActive( int currentPos ) const { return array[ currentPos ].info == ACTIVE; } /** * A hash routine for string objects. */ template int QuadraticHashTable::hash( const string & key, int tableSize ) const { int hashVal = 0; for( int i = 0; i < key.length( ); i++ ) hashVal = 37 * hashVal + key[ i ]; hashVal %= tableSize; if( hashVal < 0 ) hashVal += tableSize; return hashVal; }
  • 11. /** * A hash routine for ints. */ template int QuadraticHashTable::hash( int key, int tableSize ) const { if( key < 0 ) key = -key; return key % tableSize; } _____________________________________________________________________________ ____________ QuadraticProbing.h #ifndef _QUADRATIC_PROBING_H_ #define _QUADRATIC_PROBING_H_ #include "vector.h" #include "mystring.h" // QuadraticProbing Hash table class // // CONSTRUCTION: an initialization for ITEM_NOT_FOUND // and an approximate initial size or default of 101 // // ******************PUBLIC OPERATIONS********************* // void insert( x ) --> Insert x // void remove( x ) --> Remove x // Hashable find( x ) --> Return item that matches x // void makeEmpty( ) --> Remove all items // int hash( String str, int tableSize ) // --> Static method to hash strings class QuadraticHashTable { public: explicit QuadraticHashTable( const HashedObj & notFound, int size = 101 ); QuadraticHashTable( const QuadraticHashTable & rhs ) : ITEM_NOT_FOUND( rhs.ITEM_NOT_FOUND ),
  • 12. array( rhs.array ), currentSize( rhs.currentSize ) { } const HashedObj & find( const HashedObj & x ) const; void makeEmpty( ); void insert( const HashedObj & x ); void remove( const HashedObj & x ); const QuadraticHashTable & operator=( const QuadraticHashTable & rhs ); enum EntryType { ACTIVE, EMPTY, DELETED }; private: struct HashEntry { HashedObj element; EntryType info; HashEntry( const HashedObj & e = HashedObj( ), EntryType i = EMPTY ) : element( e ), info( i ) { } }; vector array; int currentSize; const HashedObj ITEM_NOT_FOUND; bool isPrime( int n ) const; int nextPrime( int n ) const; bool isActive( int currentPos ) const; char* findPos( const HashedObj & x ) const; char* hash( const string & key, int tableSize ) const; int hash( int key, int tableSize ) const; void rehash( ); }; #include "QuadraticProbing.cpp" #endif _____________________________________________________________________________ ____________ Dict-3-4-1.txt (Dictionary) luov vwucoxynjm lsrwwvov _____________________________________________________________________________ ____________
  • 13. Doc-3-4-1.txt (Checking for misspell words) lsrwwvov vwuboxynjm luov vwucoxynj Solution int main(int argc, char* argv[]) { char line[80], **dictionary, **document, *dictFilePtr, *docFilePtr; int *wrongs, *misspelled, misspelledCount = 0, seed, dictSize, docSize, wrongCount, tempMaxRAM, tempCurrentRAM; strcpy(line, argv[1]); strtok(line, "-"); dictSize = atoi(strtok(NULL, "-")); docSize = atoi(strtok(NULL, "-")); seed = atoi(strtok(NULL, ".")); dictionary = new char*[dictSize + 3]; dictFilePtr = readDictionary(argv[1], dictionary, dictSize); document = new char*[docSize + 3]; docFilePtr = readDocument(document, dictSize, docSize, seed); wrongs = new int[docSize]; readWrongs(wrongs, dictSize, docSize, seed, wrongCount); misspelled = new int[docSize]; CPUTimer ct; maxRAM = currentRAM = 0; Speller *speller = new Speller(dictionary, dictSize); tempMaxRAM = maxRAM; tempCurrentRAM = currentRAM; delete [] dictFilePtr; maxRAM = tempMaxRAM; currentRAM = tempCurrentRAM; speller->check(document, docSize, misspelled, &misspelledCount); cout << "CPU Time: " << ct.cur_CPUTime() << " Real RAM: " << maxRAM << endl; checkAnswers(wrongs, wrongCount, misspelled, misspelledCount);
  • 14. cleanup(dictionary, docFilePtr, document, wrongs, misspelled); delete speller; return 0; } // main()ZZ [ssdavis@lect1 p4]$ CreateDocs.out Dictionary size: 3 Document size: 4 Seed: 1 [ssdavis@lect1 p4]$ cat Dict-3-4-1.txt luov vwucoxynjm lsrwwvov [ssdavis@lect1 p4] [ssdavis@lect1 p4]$ cat Doc-3-4-1.txt lsrwwvov vwuboxynjm luov vwucoxynjm [ssdavis@lect1 p4] [ssdavis@lect1 p4]$ cat Wrongs-3-4-1.txt 1 [ssdavis@lect1 p4]$ [ssdavis@lect1 p4]$ speller.out Dict-100000-2000000-7.txt CPU Time: 0.170697 Real RAM: 1230872 [ssdavis@lect1 p4]$