# Programming Assignment 1 – Bag-based Dictionary

mde2854
ProgrammingAssignment11.zip

// From the software distribution accompanying the textbook // "A Practical Introduction to Data Structures and Algorithm Analysis, // Third Edition (C++)" by Clifford A. Shaffer. // Source code Copyright (C) 2007-2011 by Clifford A. Shaffer. #ifndef DICTIONARYADT_H #define DICTIONARYADT_H // The Dictionary abstract class. template <typename Key, typename E> class Dictionary { public: Dictionary() {} // Default constructor virtual ~Dictionary() {} // Base destructor // Reinitialize dictionary virtual void clear() = 0; // Insert a record // k: The key for the record being inserted. // e: The record being inserted. // Return true if insert is successful and false otherwise virtual bool insert(const Key& k, const E& e) = 0; // Looks for a record using the key and if found does the following: // - updates the E& rtnVal // - removes the record from the dictionary // - returns true // If the record is not found the function returns false. virtual bool remove(const Key& k, E& rtnVal) = 0; // Takes an arbitrary record from the dictionary and does the following: // - updates the E& returnValue // - removes the record from the dictionary // - returns true // If the dictionary is empty the function returns false. virtual bool removeAny(E& returnValue) = 0; // Looks for a record using the key and if found does the following: // - updates the E& returnValue // - returns true // If the record is not found the function returns false. virtual bool find(const Key& k, E& returnValue) const = 0; // Return the number of records in the dictionary. virtual int size() = 0; }; #endif

## kvpair.h

// From the software distribution accompanying the textbook // "A Practical Introduction to Data Structures and Algorithm Analysis, // Third Edition (C++)" by Clifford A. Shaffer. // Source code Copyright (C) 2007-2011 by Clifford A. Shaffer. #ifndef KVPAIR_H #define KVPAIR_H // Container for a key-value pair // Key object must be an object for which the == operator is defined. // For example, int and string will work since they both have == defined, // but Int will not work since it does not have == defined. template <typename Key, typename E> class KVpair { private: Key k; E e; public: // Constructors KVpair() {} KVpair(Key kval, E eval) { k = kval; e = eval; } KVpair(const KVpair& o) // Copy constructor { k = o.k; e = o.e; } void operator =(const KVpair& o) // Assignment operator { k = o.k; e = o.e; } bool operator==(const KVpair& o) const { if (o.k == k) { return true; } return false; } // Data member access functions Key key() { return k; } void setKey(Key ink) { k = ink; } E value() { return e; } }; #endif

## book.h

// From the software distribution accompanying the textbook // "A Practical Introduction to Data Structures and Algorithm Analysis, // Third Edition (C++)" by Clifford A. Shaffer. // Source code Copyright (C) 2007-2011 by Clifford A. Shaffer. // A collection of various macros, constants, and small functions // used for the software examples. // First, include all the standard headers that we need #ifndef BOOK_H #define BOOK_H #include <iostream> #include <cstdlib> #include <string> #include <time.h> // Used by timing functions // Now all the standard names that we use using std::cout; using std::endl; using std::string; using std::ostream; const int defaultSize = 10; // Default size // Return true iff "x" is even inline bool EVEN(int x) { return (x % 2) == 0; } // Return true iff "x" is odd inline bool ODD(int x) { return (x % 2) != 0; } // Assert: If "val" is false, print a message and terminate // the program void Assert(bool val, string s) { if (!val) { // Assertion failed -- close the program cout << "Assertion Failed: " << s << endl; exit(-1); } } // Swap two elements in a generic array template<typename E> inline void swap(E A[], int i, int j) { E temp = A[i]; A[i] = A[j]; A[j] = temp; } // Random number generator functions inline void Randomize() // Seed the generator { srand(1); } // Return a random value in range 0 to n-1 inline int Random(int n) { return rand() % (n); } // Swap two integers inline void swap(int& i, int& j) { int temp = i; i = j; j = temp; } // Swap two char*'s inline void swap(char* i, char* j) { char* temp = i; i = j; j = temp; } // Big enough for simple testing #define INFINITY 9999 // Timing variables and functions unsigned tstart = 0; // Time at beginning of timed section // Initialize the program timer void Settime() { tstart = (unsigned) clock(); } // Return the elapsed time since the last call to Settime double Gettime() { unsigned tcurr = (unsigned) clock(); return (double)(tcurr - tstart)/(double)CLOCKS_PER_SEC; } // Your basic int type as an object. class Int { private: int val; public: Int(int input=0) { val = input; } // The following is for those times when we actually // need to get a value, rather than compare objects. int key() const { return val; } // Overload = to support Int foo = 5 syntax Int operator= (int input) { val = input; return val; } }; // Let us print out Ints easily ostream& operator<<(ostream& s, const Int& i) { return s << i.key(); } ostream& operator<<(ostream& s, const Int* i) { return s << i->key(); } #endif //end of BOOK_H

## Programming Assignment 1 -- Additional Information on Bags.pptx

Programming Assignment 1 (1:7)

Build a Dictionary on top of a

Bag built on top of an

Array of objects  KVpairs (key/value pairs)

Your dictionary should be able to hold at least 10 items.

I have given you the templates for a

KV pair (implementation)

Do not modify the ADT templates or the KVPair class.

Programming Assignment 1 (2:7)

Start by writing your Approach document first. I recommend you use an incremental approach

Build the Bag first and get it working

Then build the Dictionary using the Bag and get it working.

Build your program one function at a time.

When you finish your Bag and then Dictionary show that it works using the bagtestmain.cpp file I’ve provided for you.

Programming Assignment 1 (3:7)

What is a Bag

Think of a grocery bag

Bags fill up from bottom to top (like a stack)

Unlike a stack, a bag provides access to all of the contents, not just the items at the top

To find something in a bag you start looking from the top

Programming Assignment 1 (4:7)

Dictionary

Used for storing key/value records

Provides operations for

Storing,

Finding, and

Removing records from a collection

Comparable objects

Since Find is the fundamental operation of a dictionary we need a key to search on

For the English dictionary the key is the word itself (Key) and the definition consists of the word and its definition (Value)

Dictionaries use a Key/Value pair; the key provides the “comparable object” used by Find

Programming Assignment 1 (5:7)

In implementing your Dictionary you must use the available bag operations to implement your dictionary operations.

Bag Operations

Remove(E)

RemoveTop(E)

Find(E)

EmptyBag()

BagCapicity()

Dictionary Operations:

Clear()

Insert(E)

Remove(E)

RemoveAny(E)

Find(E)

Size()

Note: You only get credit for the methods you demonstrate in your testing.

1/26/2015: Note that you’ve changed the Bag ADT so that remove(const &E) is no longer a constant to make the method similar to find().

5

Programming Assignment 1 (6:7)

KVPair.h provides the template (this is an implementation and not an ADT) for creating a key/value pair used by both the Bag and Dictionary. You do not need (nor are you allowed to) make any changes to it.

You are to use the following KV pair types for this assignment:

<int, string>

<string, int>

Programming Assignment 1 (7:7)

Example dictionary test run

In this example I am doing <int, int> and <string, string> tests.

You must do <int, string> and <string, int> tests.

My test run only shows my Dictionary run, but if you cannot get your dictionary to work you must show your Bag test runs that demonstrate every working function. You only get credit for the functions that work and to get any credit at all you need to get one or more of the Bag functions working.

7

Dictionaries & KVPairs

There you will find both details and usage examples.

You must implement the ADTs by inheriting them – you cannot modify them

class ABag : public bagADT { }

class BDictionary : public dictionaryADT { }

As a minimum you must

Demonstrate one or more working bag operations to get any credit for this assignment and

You will not get credit, even if one or more ADT operations are implemented, if your implementation does not inherit the ADTs.

If you use the implementation files I’ve provided, the inheritance issue is taken care of for you.

Data Structures and Algorithm Analysis by Cliffor A. Shaffer

Why do you think inheritance is so important here?

So that users can declare their types to be of the ADT type, which keeps their program loosely coupled to the implementation details.

The ADT acts as a contract that your implementation is required to implement. The compiler will tell you if you are not upholding your end of the contract.

9

You do not have to separate declaration and implementation into header and .cpp files

Put declaration and implementation both in the header file

I expect to see

Self-documenting code

Good use of white space and indentation

Style and your ability to follow instructions is worth 30% of the assignment.

## ABag.h

/* * File: ABag.h * Author: Prof Terri Sipantzi * * You may use this template to implement your ABag. */ #ifndef ABAG_H #define ABAG_H #include "book.h" #include "bagADT.h" template <typename E> class ABag : public Bag<E> { public: // constructors/destructor // bag methods: addItem, remove, operator+=, size, etc. private: E *data; // an array of items int used; // number of items the data array currently holds int capacity; // the number of items the bag can hold (size of array) }; #endif /* ABAG_H */

## BDictionary.h

/* * File: BDictionary.h -- implement a dictionary use an array-based bag * Author: Prof Terri Sipantzi * * You may use this template to implement your Dictionary */ #ifndef BDICTIONARY_H #define BDICTIONARY_H #include "ABag.h" #include "dictionaryADT.h" #include "kvpair.h" template <typename Key, typename E> class BDictionary : public Dictionary<Key, E> { public: // constructors/destructor // methods: clear, insert, remove, removeAny, find, size, etc. private: //Pointer to a ABag object. You'll need to instantiate the bag in your constructor: // dictionary = new ABag<KVpair<Key, E>>(size) or something similar depending on how // you've implemented your ABag constructor(s). //This pointer gives you access to the bag which stores your data and provides the //functions you need to build your dictionary. ABag<KVpair<Key, E>>* dictionary; }; #endif /* BDICTIONARY_H */

## bagtestmain.cpp

``` /* * File:   bagtestmain.cpp * Author: Prof Sipantzi -- CSIS 215 -- Programming Assignment 1 -- Bag Dictionary * * Created on July 14, 2012, 11:45 AM * Updated pointers to smart pointers in ABag and BDictionary on 12/14/2018 */ #include   < string > #include   < sstream > #include   "ABag.h" #include   "BDictionary.h" using   namespace  std ; const  size_t DICTIONARY_SIZE  =   20 ; void   PauseScreen ();   //Used to pause screen output /* * Tests BDictionary with int and string objects only. */ int  main ( int  argc ,   char **  argv )   {     cout  <<   "<Student Name> -- CSIS 215 Programming Assignment 1 -- Bag Dictionary"   <<  endl  <<  endl ;      BDictionary < int ,  string >  myIntStrDict ( DICTIONARY_SIZE );      BDictionary < string ,   int >  myStrIntDict ( DICTIONARY_SIZE );      // myIntStrDict tests      // INSERT: myIntStrDict     cout  <<   "Testing dictionary with <int, string> KV Pair\n" ;      for   ( int  i  =   1 ;  i  <=  DICTIONARY_SIZE ;  i ++ )   {         stringstream sn ;         sn  <<   "Beth "   <<  i  *   10 ;         myIntStrDict . insert ( i  *   10 ,  sn . str ());      }     cout  <<   "INSERT: Size of myIntStrDict is "   <<  myIntStrDict . size ()   <<  endl ;      // REMOVEANY: myIntStrDict     string strData ;      if   ( myIntStrDict . removeAny ( strData )   ==   true )   {         cout  <<   "REMOVEANY: My string data is "   <<  strData  <<  endl ;      }      else   {         cout  <<   "RemoveAny() failed -- dictionary is empty.\n" ;      }     cout  <<   "Size of myIntStrDict is "   <<  myIntStrDict . size ()   <<   "\n" ;      // FIND: test for myIntStrDict.find      int  intKey  =   40 ;      if   ( myIntStrDict . find ( intKey ,  strData )   ==   true )   {         cout  <<   "FIND: My data at key=="   <<  intKey  <<   " is: "   <<  strData  <<   "\n" ;         cout  <<   "Size of myIntStrDict is "   <<  myIntStrDict . size ()   <<   "\n" ;      }      else   {         cout  <<   "Could not find a record at "   <<  intKey  <<   "\n" ;      }      // REMOVE: myIntStrDict     intKey  =   60 ;      if   ( myIntStrDict . remove ( intKey ,  strData )   ==   true )   {         cout  <<   "REMOVE: Removed key "   <<  intKey  <<   " which was "   <<  strData  <<   "\n" ;      }      else   {         cout  <<   "Could not find key "   <<  intKey  <<   "\n" ;      }     cout  <<   "Size of my dictionary is "   <<  myIntStrDict . size ()   <<   "\n" ;      // CLEAR: myIntStrDict     myIntStrDict . clear ();     cout  <<   "CLEAR: Size of myIntStrDict is "   <<  myIntStrDict . size ()   <<   "\n\n" ;      /* end myIntStrDict tests ---------------------------------------------*/      // myStrIntDict tests      // INSERT: myStrIntDict     cout  <<   "Testing dictionary with <string, int> KV Pair\n" ;     myStrIntDict . insert ( "Terri" ,   57 );     myStrIntDict . insert ( "Beth" ,   53 );     myStrIntDict . insert ( "Jeremy" ,   19 );     myStrIntDict . insert ( "Nathan" ,   17 );     myStrIntDict . insert ( "Zipper" ,   2 );     myStrIntDict . insert ( "Button" ,   1 );     myStrIntDict . insert ( "Kiwi" ,   7 );     myStrIntDict . insert ( "Masoala" ,   10 );     cout  <<   "INSERT: Size of myStrIntDict is "   <<  myStrIntDict . size ()   <<  endl ;      // REMOVEANY: myStrIntDict      int  intData ;      if   ( myStrIntDict . removeAny ( intData )   ==   true )   {         cout  <<   "REMOVEANY: My int data is "   <<  intData  <<  endl ;      }      else   {         cout  <<   "RemoveAny() failed -- dictionary is empty.\n" ;      }     cout  <<   "Size of myIntStrDict is "   <<  myStrIntDict . size ()   <<   "\n" ;      // FIND: myStrIntDict.find     string strKey  =   "Kiwi" ;      if   ( myStrIntDict . find ( strKey ,  intData )   ==   true )   {         cout  <<   "FIND: "   <<  strKey  <<   "\'s age is "   <<  intData  <<  endl ;         cout  <<   "Size of myStrIntDict is "   <<  myStrIntDict . size ()   <<   "\n" ;      }      else   {         cout  <<   "Could not find a record at "   <<  strKey  <<   "\n" ;      }      // REMOVE: myStrIntDict     strKey  =   "Button" ;      if   ( myStrIntDict . remove ( strKey ,  intData )   ==   true )   {         cout  <<   "REMOVE: Removed key "   <<  strKey  <<   " which was "   <<  intData  <<   "\n" ;      }      else   {         cout  <<   "Could not find key "   <<  strKey  <<   "\n" ;      }     cout  <<   "Size of my dictionary is "   <<  myStrIntDict . size ()   <<   "\n" ;      // CLEAR: myStrIntDict     myStrIntDict . clear ();     cout  <<   "CLEAR: Size of myStrIntDict is "   <<  myStrIntDict . size ()   <<   "\n\n" ;      /* end myStrIntDict tests ---------------------------------------------*/      /* Demonstrate any Bag functions that were not used/demonstrated in the implemention      of your BDictionary and ABag using a Bag of KVpairs<int, string>. */      ABag < KVpair < int ,  string >>  myBag ;   //Used to test bag functions not previously demonstrated      PauseScreen ();      return   0 ; } //Used to pause the screen wherever desired void   PauseScreen () {      char  ch ;     cout  <<   "\nPress the Enter key to continue ... " ;     cin . get ( ch ); } ```