1
0

added more code

This commit is contained in:
Andrew W 2022-08-28 16:12:16 -05:00
parent 5a2894ed1b
commit 7dabaef6f6
2345 changed files with 1343530 additions and 0 deletions

View File

@ -0,0 +1,36 @@
#include <iostream>
#include "DateType.h"
using namespace std;
void DateType::Initialize (int newMonth, int newDay, int newYear)
{
year=newYear;
month=newMonth;
day=newDay;
}
int DateType::GetMonth() const
{
return month;
}
int DateType::GetYear() const
{
return year;
}
int DateType::GetDay() const
{
return day;
}
int main()
{
DateType today;
DateType anotherDay;
today.Initialize(9,24,2003);
anotherDay.Initialize(9,25,2003);
cout << "Today is " << today.GetMonth() << "/" << today.GetDay() << "/" << today.GetYear()<< endl;
cout << "Another date is " << anotherDay.GetMonth() << "/" << anotherDay.GetDay() << "/" << anotherDay.GetYear() << endl;
}

BIN
CPE212/Project 1.1/DateType.exe Executable file

Binary file not shown.

View File

@ -0,0 +1,12 @@
class DateType
{
private:
int year;
int month;
int day;
public:
void Initialize(int newMonth, int newDay, int newYear);
int GetYear() const;
int GetMonth() const;
int GetDay() const;
};

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

173
CPE212/Project_01/main.cpp Normal file
View File

@ -0,0 +1,173 @@
//
// main.cpp -- Project01, CPE212 Fall 2010 -- C++ Review Project
//
// Driver program for Image Processing Program which is used to test each
// image processing operation.
//
// DO NOT SUBMIT OR SUBMIT THIS FILE
//
// List of allowed include files appear below
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // Global using declaration
// Global Constants -- you may use these global constants in your code
const int MAXROWS = 10; // Maximum number of rows in image
const int MAXCOLS = 10; // Maximum number of columns in image
// Function Prototypes for functions included at the end of main.cpp
void Print(const int image[MAXROWS][MAXCOLS]);
void Bars();
// Function Prototypes for the functions you must implement in project01.cpp
void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS]);
void FlipHorizontal(int image[MAXROWS][MAXCOLS]);
void FlipVertical(int image[MAXROWS][MAXCOLS]);
void RotateCW(int image[MAXROWS][MAXCOLS]);
void RotateCCW(int image[MAXROWS][MAXCOLS]);
void Transpose(int image[MAXROWS][MAXCOLS]);
// Start of main() function
int main (int argc, char * const argv[]) // Command-line arguments (more on this later)
{
ifstream inputs; // Input file stream variable for test file
char op, ch; // Hold operation and optional char input from test file
string comment; // Holds comment string input from test file
int image[MAXROWS][MAXCOLS]; // Array of integers representing image
string imagefile; // Name of image file
// Output usage message if test input file name is not provided
if (argc != 2)
{
cout << "Usage:\n project01 <inputfile>\n";
return 1;
}
// Attempt to open test input file -- terminate if file does not open
inputs.open(argv[1]);
if (!inputs)
{
cout << "Error - unable to open input file" << endl;
return 1;
}
// Process comment line from input file
getline(inputs, comment); // Input file header comment
cout << endl << comment << endl << endl; // Output file header comment
// Below is primary loop that processes each operation appearing within the test file.
// Starts with an initial priming read of first operation
inputs >> op; // Attempt to input first test operation from file
while (inputs) // While Not-EOF
{
switch (op) // Process operation input from test file
{
case '#': // Test file comment
getline(inputs, comment); // Input and echo the comment appearing in the test file
cout << '#' << comment << endl;
break;
case 'p': // Print Grid
Print(image); // Function definition appears at the end of this file
break;
case 'b': // Print Bars
Bars(); // Function definition appears at the end of this file
break;
case 'i': // Load Image
inputs >> imagefile; // Input name of imagefile from test file
LoadImage(imagefile, image); // Implement this function in project01.cpp
break;
case '+': // Rotate Image Clockwise 90 Degrees
RotateCW(image); // Implement this function in project01.cpp
break;
case '-': // Rotate Image Counterclockwise 90 Degrees
RotateCCW(image); // Implement this function in project01.cpp
break;
case 'v': // Flip Image Vertical
FlipVertical(image); // Implement this function in project01.cpp
break;
case 'h': // Flip Image Horizontal
FlipHorizontal(image); // Implement this function in project01.cpp
break;
case 't': // Transpose Image Across Major Diagonal
Transpose(image); // Implement this function in project01.cpp
break;
default: // Error
cout << "Error - unrecognized operation '" << op << "'" << endl;
cout << "Terminating now..." << endl;
return 1;
break;
}
cout << endl;
inputs >> op; // Attempt to input next command
}
return 0;
}
/************** Implementation of Print() and Bars() functions ********************/
// DO NOT MODIFY THIS CODE
void Print(const int image[MAXROWS][MAXCOLS])
// Print() -- outputs image row-by-row in desired format substituting
// * for 1 and - for 0.
{
for(int r=0; r < MAXROWS; r++) // Loop to visit each row in image
{
for(int c=0; c < MAXCOLS; c++) // Loop to output every element on crrent row
{
if (image[r][c] == 1) // Output appropriate symbol
{
cout << '*';
}
else if (image[r][c] == 0)
{
cout << '-';
}
else
{
cout << 'X';
}
}
cout << endl;
}
} // End Print()
void Bars()
// Bars() -- prints two horizontal rows of bars
{
cout << "#################################################################" << endl;
cout << "#################################################################" << endl;
} // End Bars()
/************** DO NOT DELETE *************/
// The preprocessor directive below will import the function definitions
// from the file project01.cpp and place them at the end of this file creating an
// Expanded Source File which is forwarded to the compiler for compilation.
#include "project01.cpp"
/************** End of main.cpp ***************/

View File

@ -0,0 +1,9 @@
# Project01 -- Fall 2010 CPE212-01
project01: project01.cpp main.cpp
g++ main.cpp -o project01
clean:
rm project01

View File

@ -0,0 +1,13 @@
# p01image1.txt -- Sample Image #1
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 1 1 1 1 0 0 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

View File

@ -0,0 +1,13 @@
# p01image2.txt -- Sample Image #2
0 1 1 1 0 1 0 0 0 1
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 1
0 0 0 1 1 0 0 0 0 0
0 0 0 1 1 1 1 0 0 1
1 0 0 1 1 1 1 0 0 0
1 0 0 1 1 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
1 0 0 0 0 1 1 1 1 0

View File

@ -0,0 +1,13 @@
# p01image3.txt -- Sample Image #3
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 1 1 0 0 0 0 0 0 0
1 1 1 0 0 0 0 0 0 0

View File

@ -0,0 +1,77 @@
# p01input1.txt -- Test of Transpose Image
# Draw Bars
b
# Load Image1
i p01image1.txt
# Print Image1
p
# Transpose Image1
t
# Print Image1
p
# Transpose Image1
t
# Print Image1
p
# Draw Bars
b
# Load Image2
i p01image2.txt
# Print Image2
p
# Transpose Image2
t
# Print Image2
p
# Transpose Image2
t
# Print Image2
p
# Draw Bars
b
# Load Image3
i p01image3.txt
# Print Image3
p
# Transpose Image3
t
# Print Image3
p
# Transpose Image3
t
# Print Image3
p
# Draw Bars
b

View File

@ -0,0 +1,74 @@
# p01input2.txt -- Test of Horizontal Flip
# Draw Bars
b
# Load Image1
i p01image1.txt
# Print Image1
p
# Horizontal Flip Image1
h
# Print Flipped Image1
p
# Horizontal Flip Image1
h
# Print Flipped Image1
p
# Draw Bars
b
# Load Image2
i p01image2.txt
# Print Image2
p
# Horizontal Flip Image2
h
# Print Flipped Image2
p
# Horizontal Flip Image2
h
# Print Flipped Image2
p
# Draw Bars
b
# Load Image3
i p01image3.txt
# Print Image3
p
# Horizontal Flip Image3
h
# Print Flipped Image3
p
# Horizontal Flip Image3
h
# Print Flipped Image3
p
# Draw Bars
b

View File

@ -0,0 +1,74 @@
# p01input3.txt -- Test of Vertical Flip
# Draw Bars
b
# Load Image1
i p01image1.txt
# Print Image1
p
# Vertical Flip Image1
v
# Print Flipped Image1
p
# Vertical Flip Image1
v
# Print Flipped Image1
p
# Draw Bars
b
# Load Image2
i p01image2.txt
# Print Image2
p
# Vertical Flip Image2
v
# Print Flipped Image2
p
# Vertical Flip Image2
v
# Print Flipped Image2
p
# Draw Bars
b
# Load Image3
i p01image3.txt
# Print Image3
p
# Vertical Flip Image3
v
# Print Flipped Image3
p
# Vertical Flip Image3
v
# Print Flipped Image3
p
# Draw Bars
b

View File

@ -0,0 +1,117 @@
# p01input4.txt -- Test of Rotate Clockwise
# Draw Bars
b
# Load Image1
i p01image1.txt
# Print Image1
p
# Rotate Clockwise 90 Degrees Image1
+
# Print Rotated Image1
p
# Rotate Clockwise 90 Degrees Image1
+
# Print Rotated Image1
p
# Rotate Clockwise 90 Degrees Image1
+
# Print Rotated Image1
p
# Rotate Clockwise 90 Degrees Image1
+
# Print Rotated Image1
p
# Draw Bars
b
# Load Image2
i p01image2.txt
# Print Image2
p
# Rotate Clockwise 90 Degrees Image2
+
# Print Rotated Image2
p
# Rotate Clockwise 90 Degrees Image2
+
# Print Rotated Image2
p
# Rotate Clockwise 90 Degrees Image2
+
# Print Rotated Image2
p
# Rotate Clockwise 90 Degrees Image2
+
# Print Rotated Image2
p
# Draw Bars
b
# Load Image3
i p01image3.txt
# Print Image3
p
# Rotate Clockwise 90 Degrees Image3
+
# Print Rotated Image3
p
# Rotate Clockwise 90 Degrees Image3
+
# Print Rotated Image3
p
# Rotate Clockwise 90 Degrees Image3
+
# Print Rotated Image3
p
# Rotate Clockwise 90 Degrees Image3
+
# Print Rotated Image3
p
# Draw Bars
b

View File

@ -0,0 +1,117 @@
# p01input5.txt -- Test of Rotate Counter Clockwise
# Draw Bars
b
# Load Image1
i p01image1.txt
# Print Image1
p
# Rotate Counter Clockwise 90 Degrees Image1
-
# Print Rotated Image1
p
# Rotate Counter Clockwise 90 Degrees Image1
-
# Print Rotated Image1
p
# Rotate Counter Clockwise 90 Degrees Image1
-
# Print Rotated Image1
p
# Rotate Counter Clockwise 90 Degrees Image1
-
# Print Rotated Image1
p
# Draw Bars
b
# Load Image2
i p01image2.txt
# Print Image2
p
# Rotate Counter Clockwise 90 Degrees Image2
-
# Print Rotated Image2
p
# Rotate Counter Clockwise 90 Degrees Image2
-
# Print Rotated Image2
p
# Rotate Counter Clockwise 90 Degrees Image2
-
# Print Rotated Image2
p
# Rotate Counter Clockwise 90 Degrees Image2
-
# Print Rotated Image2
p
# Draw Bars
b
# Load Image3
i p01image3.txt
# Print Image3
p
# Rotate Counter Clockwise 90 Degrees Image3
-
# Print Rotated Image3
p
# Rotate Counter Clockwise 90 Degrees Image3
-
# Print Rotated Image3
p
# Rotate Counter Clockwise 90 Degrees Image3
-
# Print Rotated Image3
p
# Rotate Counter Clockwise 90 Degrees Image3
-
# Print Rotated Image3
p
# Draw Bars
b

BIN
CPE212/Project_01/project01 Normal file

Binary file not shown.

View File

@ -0,0 +1,155 @@
/*
Noah Woodlee
CPE212-01
Project 1, due Sunday, Febuary 21, 2020
*/
#include <iostream>
#include <fstream>
#include <string>
// LoadImage defintion
void LoadImage(const string imagefile, int image[MAXROWS][MAXCOLS])
{
ifstream input;
input.open(imagefile.c_str());
if (!input)
{
cout << "Error - File unable to be opened." << endl;
return;
}
int rows, cols, nums;
string str;
getline(input, str);
//cout << str;
for (int r = 0; r < MAXROWS ; r++) // iterate number of rows
{
for (int c = 0; c < MAXCOLS; c++) // iterate number of columns
{
input >> nums;
image[r][c]=nums;
}
}
} // End of LoadImage
// Flip Horozontal defintion
void FlipHorizontal(int image[MAXROWS][MAXCOLS])
{
int temp;
for (int r = 0; r < MAXROWS; r++) // loop for columns 1 & 10
{
temp=image[r][0];
image[r][0]=image[r][MAXCOLS-1];
image[r][MAXCOLS-1]=temp;
}
for (int r = 0; r < MAXROWS; r++) // loop for columns 2 & 9
{
temp=image[r][1];
image[r][1]=image[r][MAXCOLS-2];
image[r][MAXCOLS-2]=temp;
}
for (int r = 0; r < MAXROWS; r++) // loop for columns 3 & 8
{
temp=image[r][2];
image[r][2]=image[r][MAXCOLS-3];
image[r][MAXCOLS-3]=temp;
}
for (int r = 0; r < MAXROWS; r++) // loop for column 4 & 7
{
temp=image[r][3];
image[r][3]=image[r][MAXCOLS-4];
image[r][MAXCOLS-4]=temp;
}
for (int r = 0; r < MAXROWS; r++) // loop for column 5 & 6
{
temp=image[r][4];
image[r][4]=image[r][MAXCOLS-5];
image[r][MAXCOLS-5]=temp;
}
} // End of FlipHorizontal function
// FlipVertical defintion
void FlipVertical(int image[MAXROWS][MAXCOLS])
{
int temp;
for (int c = 0; c < MAXCOLS; c++) // loop for rows 1 & 10
{
temp = image[0][c];
image[0][c] = image[MAXROWS-1][c];
image[MAXROWS-1][c] = temp;
}
for (int c = 0; c < MAXCOLS; c++) // loop for rows 2 & 9
{
temp = image[1][c];
image[1][c] = image[MAXROWS-2][c];
image[MAXCOLS-2][c] = temp;
}
for (int c = 0; c < MAXCOLS; c++) // loop for rows 3 & 8
{
temp = image[2][c];
image[2][c] = image[MAXROWS-3][c];
image[MAXCOLS-3][c]=temp;
}
for (int c = 0; c < MAXCOLS; c++) // loop for rows 4 & 7
{
temp = image[3][c];
image[3][c] = image[MAXROWS-4][c];
image[MAXCOLS-4][c] = temp;
}
for (int c = 0; c < MAXCOLS; c++) // loop for rows 5 & 6
{
temp = image[4][c];
image[4][c] = image[MAXROWS-5][c];
image[MAXCOLS-5][c] = temp;
}
}
// RotateCW defintion
void RotateCW(int image[MAXROWS][MAXCOLS])
{
int n = MAXCOLS;
for (int i = 0; i < n/2; i++)
{
for (int j = i; j < n-i-1; j++)
{
int temp = image[i][j];
image[i][j]=image[n-1-j][i];
image[n - 1 - j][i] = image[n - 1 - i][n - 1 - j];
image[n - 1 - i][n - 1 - j] = image[j][n - 1 - i];
image[j][n - 1 - i] = temp;
}
}
}
// RotateCCW defintion
void RotateCCW(int image[MAXROWS][MAXCOLS])
{
int n=MAXROWS;
for(int i=0;i<n/2;i++)
{
for(int j=i;j<n-i-1;j++)
{
int temp=image[i][j];
image[i][j]=image[j][n-i-1];
image[j][n-i-1]=image[n-i-1][n-j-1];
image[n-i-1][n-j-1]=image[n-j-1][i];
image[n-j-1][i]=temp;
}
}
}
// Transpose defintion
void Transpose(int image[MAXROWS][MAXCOLS])
{
int temp;
for (int r = 0; r < MAXROWS; r++){ // loop to increment rows
for (int c = 0; c < r; c++) // loop to increment columns
{
temp = image[r][c];
image[r][c] = image[c][r];
image[c][r] = temp;
}
}
}

Binary file not shown.

View File

@ -0,0 +1,39 @@
// blackcard.cpp inherits from card
#include "blackcard.h"
BlackCard::BlackCard(int v) : Card::Card(v) // Parameterized constructor that creates a black card with value v and unknown suit
{
Card::SetColor("black"); // set color to black
}
string BlackCard::Description() const // Outputs card characteristics - value and color as a string
{
int Bval = Card::GetValue();
string Bcol = Card::GetColor();
string d = "Value = "; // temporary variable used to accumulate result
switch (Bval) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
d=d+", Color = "; // adds color to output string
if (Bcol=="black") d=d + "black";
if (Bcol=="red") d=d + "red";
else d=+ "unknown";
return d; // Return string describing card value
}

View File

@ -0,0 +1,28 @@
//
// blackcard.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// DO NOT MODIFY OR SUBMIT THIS FILE!!!
//
#ifndef BLACKCARD_H
#define BLACKCARD_H
#include "card.h"
class BlackCard : public Card
{
private:
// No additional private members
public:
// Constructors
BlackCard(int v); // Creates a black card with value v and unknown suit
string Description() const; // Outputs card characteristics - value and color as a string
// Hint: use base class Description method to generate part of
// the description and append the color information at the end
};
#endif

Binary file not shown.

View File

@ -0,0 +1,99 @@
//
// card.cpp -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// Add the missing statements to complete each method below
// and SUBMIT this file for grading !!!
//
#include <iostream>
#include <cstdlib>
#include "card.h"
Card::Card()
// Default Constructor: Initializes value to 0, color to "unknown", and suit to 'U'
{
value=0;
color = "Unknown";
suit = 'U';
}
Card::Card(int v)
// Parameterized Constructor: Initializes value to v, color to "unknown", and suit to 'U'
{
value=v;
color = "Unknown";
suit = 'U';
}
int Card::GetValue() const
// Returns variable value
{
return value;
}
string Card::GetColor() const
// Returns variable color
{
return color;
}
char Card::GetSuit() const
// Returns variable suit
{
return suit;
}
void Card::SetValue(int v)
// Sets value to v
{
value = v;
}
void Card::SetColor(string c)
// Sets color to c
{
color = c;
}
void Card::SetSuit(char s)
// Sets suit to s
{
suit = s;
}
string Card::Description() const
// Outputs card characteristics - value as a string
// DO NOT MODIFY THIS METHOD !!!!
{
string d = "Value = "; // temporary variable used to accumulate result
switch (value) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
return d; // Return string describing card value
}

48
CPE212/Project_02/card.h Normal file
View File

@ -0,0 +1,48 @@
//
// card.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// Add the missing statements to complete the class declaration below
// and SUBMIT this file for grading !!!
//
#include <string>
using namespace std;
#ifndef CARD_H
#define CARD_H
class Card // Class modeling Card ADT
{
private:
int value; // Card value: 2-10 for number cards, 11-14 for JQKA; 0 for unknown
string color; // Card color: "red", "black", or "unknown"
char suit; // Card suit: 'H' for hearts, 'D' for diamonds, 'C' for clubs, 'S' for spades or 'U' for unknown
public:
//******** Add Constructor Prototypes Below *********//
Card(); // Default constructor prototype: creates card with value v, color unknown, and suit U
Card(int v); // Parameterized constructor prototype: creates card with value v, color unknown, and suit U
//******** Add Transformer Prototypes Below *********//
void SetValue(int v); // SetValue prototype: Sets card value equal to v
void SetColor(string c); // SetColor prototype: Sets color value equal to c
void SetSuit(char s); // SetSuit prototype: Sets suit value equal to s
//******** Add Observer Prototypes Below *********//
int GetValue() const; // GetValue prototype: Returns current value of value
string GetColor() const; // GetColor prototype: Returns current value of color
char GetSuit() const; // GetSuit prototype: Returns current value of suit
virtual string Description() const; // Description prototype: Polymorphic Function!!!
// Outputs card characteristics - value as a string (see sample output from p01input1.txt)
};
#endif

BIN
CPE212/Project_02/card.o Normal file

Binary file not shown.

View File

@ -0,0 +1,51 @@
// club inherits from blackcard
#include "club.h"
Club::Club(int v) : BlackCard::BlackCard(v) // Parameterized constructor that creates a black card with value v and unknown suit
{
Club::SetSuit('C'); // sets suit to C
BlackCard::SetColor("black");
}
string Club::Description() const // Outputs card characteristics - value and color and suit as a string
{
int Cval = BlackCard::GetValue();
string Ccol = BlackCard::GetColor();
char Cst = BlackCard::GetSuit();
string d = "Value = "; // temporary variable used to accumulate result
switch (Cval) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
d = d + ", Color = "; // adds color to output string
if (Ccol=="black") d = d + "black";
if (Ccol=="red") d = d + "red";
else d=+ "unknown";
// appends suit to output string
d =+ ", Suit = ";
switch (Cst)
{
case 'H': d =+ "H"; break;
case 'C': d =+ 'C'; break;
case 'D': d =+ 'D'; break;
case 'U': d =+ 'U'; break;
}
return d; // Return string describing card value
}

27
CPE212/Project_02/club.h Normal file
View File

@ -0,0 +1,27 @@
//
// club.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// DO NOT MODIFY OR SUBMIT THIS FILE!!!
//
#ifndef CLUB_H
#define CLUB_H
#include "blackcard.h"
class Club : public BlackCard
{
private:
// No additional private members
public:
// Constructors
Club(int v); // Creates a black club card with value v
string Description() const; // Outputs card characteristics - value, color, suit
// Hint: use base class Description method to generate part of
// the description and append the suit information at the end
};
#endif

BIN
CPE212/Project_02/club.o Normal file

Binary file not shown.

View File

@ -0,0 +1,51 @@
// Diamond inherits from redcard
#include "diamond.h"
Diamond::Diamond(int v) : RedCard::RedCard(v) // Parameterized constructor that creates a black card with value v and suit s
{
Card::SetSuit('D'); // sets suit to D
}
RedCard::Card di; // allows access to functions in Card
string Diamond::Description() const // Outputs card characteristics - value and color and suit as a string
{
int Dval = Card::GetValue();
string Dcol = Card::GetColor();
char Dst = Card::GetSuit();
string d = "Value = "; // temporary variable used to accumulate result
switch (Dval) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
d = d + ", Color = "; // adds color to output string
if (Dcol=="black") d = d + "black";
if (Dcol=="red") d = d + "red";
else d=+ "unknown";
// appends suit to output string
d =+ ", Suit = ";
switch (Dst)
{
case 'H': d =+ "H"; break;
case 'C': d =+ 'C'; break;
case 'D': d =+ 'D'; break;
case 'U': d =+ 'U'; break;
}
return d; // Return string describing card value
}

View File

@ -0,0 +1,27 @@
//
// diamond.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// DO NOT MODIFY OR SUBMIT THIS FILE!!!
//
#ifndef DIAMOND_H
#define DIAMOND_H
#include "redcard.h"
class Diamond : public RedCard
{
private:
// No additional private members
public:
// Constructors
Diamond(int v); // Creates a red diamond card with value v
string Description() const; // Outputs card characteristics - value, color, suit
// Hint: use base class Description method to generate part of
// the description and append the suit information at the end
};
#endif

BIN
CPE212/Project_02/diamond.o Normal file

Binary file not shown.

View File

@ -0,0 +1,51 @@
// heart inherits from redcard
#include "heart.h"
Heart::Heart(int v) : RedCard::RedCard(v) // Parameterized constructor that creates a black card with value v and unknown suit
{
Card::SetSuit('H'); // sets suit to H
}
RedCard::Card ht; // allows access to functions in Card
string Heart::Description() const // Outputs card characteristics - value and color and suit as a string
{
int Hval = Card::GetValue();
string Hcol = Card::GetColor();
char Hst = Card::GetSuit();
string d = "Value = "; // temporary variable used to accumulate result
switch (Hval) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
d = d + ", Color = "; // adds color to output string
if (Hcol=="black") d = d + "black";
if (Hcol=="red") d = d + "red";
else d=+ "unknown";
// appends suit to output string
d =+ ", Suit = ";
switch (Hst)
{
case 'H': d =+ "H"; break;
case 'C': d =+ 'C'; break;
case 'D': d =+ 'D'; break;
case 'U': d =+ 'U'; break;
}
return d; // Return string describing card value
}

28
CPE212/Project_02/heart.h Normal file
View File

@ -0,0 +1,28 @@
//
// heart.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// DO NOT MODIFY OR SUBMIT THIS FILE!!!
//
#ifndef HEART_H
#define HEART_H
#include "redcard.h"
class Heart : public RedCard
{
private:
// No additional private members
public:
// Constructors
Heart(int v); // Creates a red heart card with value v
string Description() const; // Outputs card characteristics - value, color, suit
// Hint: use base class Description method to generate part of
// the description and append the suit information at the end
};
#endif

BIN
CPE212/Project_02/heart.o Normal file

Binary file not shown.

148
CPE212/Project_02/main.cpp Normal file
View File

@ -0,0 +1,148 @@
//
// main.cpp -- Project02, CPE212 Fall 2010 -- Classes
//
// Driver program for Card program which is used to test each
// class member function.
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
// List of allowed include files appear below
#include <iostream>
#include <fstream>
#include <string>
#include "card.h"
#include "heart.h"
#include "diamond.h"
#include "club.h"
#include "spade.h"
using namespace std; // Global using declaration
void Bar(); // Prototype for Bar function
void Print(Card* someCard); // Prototype for Print function
// Start of main() function
int main (int argc, char * const argv[]) // Command-line arguments (more on this later)
{
ifstream inputs; // Input file stream variable for test file
char op, ch; // Hold operation and optional char input from test file
string comment; // Holds comment string input from test file
Card* ptr = NULL; // Pointer to the current card
int v; // Holds card value input from test file
// Output usage message if test input file name is not provided
if (argc != 2)
{
cout << "Usage:\n project02 <inputfile>\n";
return 1;
}
// Attempt to open test input file -- terminate if file does not open
inputs.open(argv[1]);
if (!inputs)
{
cout << "Error - unable to open input file" << endl;
return 1;
}
// Process comment line from input file
getline(inputs, comment); // Input file header comment
cout << endl << comment << endl << endl; // Output file header comment
// Below is the primary loop that processes each operation appearing within the test file.
// Starts with an initial priming read of first operation
inputs >> op; // Attempt to input first test operation from file
while (inputs) // While Not-EOF
{
switch (op) // Process operation input from test file
{
case '#': // Test file comment
getline(inputs, comment); // Input and echo the comment appearing in the test file
cout << '#' << comment << endl;
break;
case 'p': // Print Card
Print(ptr);
cout << endl;
break;
case 'b': // Print Bar
Bar(); // Function definition appears at the end of this file
break;
case '+': // Constructor
inputs >> op; // Input card type into op
try
{
switch (op) // Invoke requested constructor with argument as required
{
case 'h': inputs >> v; cout << "Heart(" << v << ") -- "; ptr = new Heart(v); break;
case 'd': inputs >> v; cout << "Diamond(" << v << ") -- "; ptr = new Diamond(v); break;
case 'c': inputs >> v; cout << "Club(" << v << ") -- "; ptr = new Club(v); break;
case 's': inputs >> v; cout << "Spade(" << v << ") -- "; ptr = new Spade(v); break;
case 'b': inputs >> v; cout << "BlackCard(" << v << ") -- "; ptr = new BlackCard(v); break;
case 'r': inputs >> v; cout << "RedCard(" << v << ") -- "; ptr = new RedCard(v); break;
case 'x': inputs >> v; cout << "Card(" << v << ") -- "; ptr = new Card(v); break;
case 'z': cout << "Card() -- "; ptr = new Card; break;
default: cout << "Error: Unknown Card Type"; ptr = NULL; break;
}
cout << "Successful";
}
catch ( ... ) // Catch any exception thrown above
{
cout << "Failed";
}
cout << endl;
break;
case '-': // Destructor
delete ptr; // Deallocate card
ptr = NULL; // Make sure that ptr is not a dangling pointer
break;
default: // Error
cout << "Error - unrecognized operation '" << op << "'" << endl;
cout << "Terminating now..." << endl;
return 1;
break;
}
//cout << endl;
inputs >> op; // Attempt to input next command
}
return 0;
}
/************** Implementation of Print() and Bar() functions ********************/
// DO NOT MODIFY THIS CODE
void Bar()
// Bar() -- prints horizontal bar
{
cout << "#################################################################" << endl;
} // End Bar()
void Print(Card* someCard)
// Writes description of card to stdout
{
cout << someCard->Description(); // Hint: Polymorphic function
}
/************** End of main.cpp ***************/

BIN
CPE212/Project_02/main.o Normal file

Binary file not shown.

View File

@ -0,0 +1,43 @@
# Project02 Makefile -- CPE 212-01, Fall 2010
project02: main.o card.o redcard.o blackcard.o heart.o diamond.o club.o spade.o
g++ main.o card.o redcard.o blackcard.o heart.o diamond.o club.o spade.o -o project02
main.o: main.cpp card.h redcard.h blackcard.h heart.h diamond.h club.h spade.h
g++ -c main.cpp
card.o: card.cpp card.h
g++ -c card.cpp
redcard.o: redcard.cpp redcard.h card.h
g++ -c redcard.cpp
blackcard.o: blackcard.cpp blackcard.h card.h
g++ -c blackcard.cpp
heart.o: heart.cpp heart.h redcard.h card.h
g++ -c heart.cpp
diamond.o: diamond.cpp diamond.h redcard.h card.h
g++ -c diamond.cpp
club.o: club.cpp club.h blackcard.h card.h
g++ -c club.cpp
spade.o: spade.cpp spade.h blackcard.h card.h
g++ -c spade.cpp
# Remove executable and all object files if they exist
clean:
rm *.o project02

View File

@ -0,0 +1,67 @@
# p02input1.txt - Test Card Class
b
# Test of default constructor
+ z
p
-
b
# Test of parameterized constructor
+ x 2
p
-
b
# Test of parameterized constructor
+ x 9
p
-
b
# Test of parameterized constructor
+ x 10
p
-
b
# Test of parameterized constructor
+ x 11
p
-
b
# Test of parameterized constructor
+ x 12
p
-
b
# Test of parameterized constructor
+ x 13
p
-
b
# Test of parameterized constructor
+ x 14
p
-
b
# Test of parameterized constructor
+ x 15
p
-
b

View File

@ -0,0 +1,67 @@
# p02input2.txt - Test RedCard Class
b
# Test of parameterized constructor
+ r 1
p
-
b
# Test of parameterized constructor
+ r 2
p
-
b
# Test of parameterized constructor
+ r 9
p
-
b
# Test of parameterized constructor
+ r 10
p
-
b
# Test of parameterized constructor
+ r 11
p
-
b
# Test of parameterized constructor
+ r 12
p
-
b
# Test of parameterized constructor
+ r 13
p
-
b
# Test of parameterized constructor
+ r 14
p
-
b
# Test of parameterized constructor
+ r 15
p
-
b

View File

@ -0,0 +1,68 @@
# p02input3.txt - Test BlackCard Class
b
# Test of parameterized constructor
+ b 1
p
-
b
# Test of parameterized constructor
+ b 2
p
-
b
# Test of parameterized constructor
+ b 9
p
-
b
# Test of parameterized constructor
+ b 10
p
-
b
# Test of parameterized constructor
+ b 11
p
-
b
# Test of parameterized constructor
+ b 12
p
-
b
# Test of parameterized constructor
+ b 13
p
-
b
# Test of parameterized constructor
+ b 14
p
-
b
# Test of parameterized constructor
+ b 15
p
-
b

View File

@ -0,0 +1,141 @@
# p02input4.txt - Test Heart and Diamond Classes
b
# Test of Heart Class
b
# Test of parameterized constructor
+ h 1
p
-
b
# Test of parameterized constructor
+ h 2
p
-
b
# Test of parameterized constructor
+ h 9
p
-
b
# Test of parameterized constructor
+ h 10
p
-
b
# Test of parameterized constructor
+ h 11
p
-
b
# Test of parameterized constructor
+ h 12
p
-
b
# Test of parameterized constructor
+ h 13
p
-
b
# Test of parameterized constructor
+ h 14
p
-
b
# Test of parameterized constructor
+ h 15
p
-
b
b
# Test of Diamond Class
b
# Test of parameterized constructor
+ d 1
p
-
b
# Test of parameterized constructor
+ d 2
p
-
b
# Test of parameterized constructor
+ d 9
p
-
b
# Test of parameterized constructor
+ d 10
p
-
b
# Test of parameterized constructor
+ d 11
p
-
b
# Test of parameterized constructor
+ d 12
p
-
b
# Test of parameterized constructor
+ d 13
p
-
b
# Test of parameterized constructor
+ d 14
p
-
b
# Test of parameterized constructor
+ d 15
p
-
b

View File

@ -0,0 +1,141 @@
# p02input5.txt - Test Club and Spade Classes
b
# Test of Club Class
b
# Test of parameterized constructor
+ c 1
p
-
b
# Test of parameterized constructor
+ c 2
p
-
b
# Test of parameterized constructor
+ c 9
p
-
b
# Test of parameterized constructor
+ c 10
p
-
b
# Test of parameterized constructor
+ c 11
p
-
b
# Test of parameterized constructor
+ c 12
p
-
b
# Test of parameterized constructor
+ c 13
p
-
b
# Test of parameterized constructor
+ c 14
p
-
b
# Test of parameterized constructor
+ c 15
p
-
b
b
# Test of Spade Class
b
# Test of parameterized constructor
+ s 1
p
-
b
# Test of parameterized constructor
+ s 2
p
-
b
# Test of parameterized constructor
+ s 9
p
-
b
# Test of parameterized constructor
+ s 10
p
-
b
# Test of parameterized constructor
+ s 11
p
-
b
# Test of parameterized constructor
+ s 12
p
-
b
# Test of parameterized constructor
+ s 13
p
-
b
# Test of parameterized constructor
+ s 14
p
-
b
# Test of parameterized constructor
+ s 15
p
-
b

BIN
CPE212/Project_02/project02 Normal file

Binary file not shown.

View File

@ -0,0 +1,40 @@
// redcard inherits from card
#include "redcard.h"
RedCard::RedCard(int v) : Card::Card(v) // Parameterized constructor that creates a red card with value v and unknown suit
{
Card::SetColor("red");
}
string RedCard::Description() const // Outputs card characteristics - value and color as a string
{
int Rval = Card::GetValue();
string Rcol = Card::GetColor();
string d = "Value = "; // temporary variable used to accumulate result
switch (Rval) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
d = d + ", Color = "; // adds color to output string
if (Rcol=="black") d = d + "black";
if (Rcol=="red") d = d + "red";
else d=+ "unknown";
return d; // Return string describing card value
}

View File

@ -0,0 +1,27 @@
//
// redcards.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// DO NOT MODIFY OR SUBMIT THIS FILE!!!
//
#ifndef REDCARD_H
#define REDCARD_H
#include "card.h"
class RedCard : public Card
{
private:
// No additional private members
public:
// Constructors
RedCard(int v); // Creates a red card with value v and unknown suit
string Description() const; // Outputs card characteristics - value and color as a string
// Hint: use base class Description method to generate part of
// the description and append the color information at the end
};
#endif

BIN
CPE212/Project_02/redcard.o Normal file

Binary file not shown.

View File

@ -0,0 +1,52 @@
// spade inherits from blackcard
#include "spade.h"
Spade::Spade(int v) : BlackCard::BlackCard(v) // Parameterized constructor that creates a black card with value v and unknown suit
{
Card::SetSuit('S'); // sets suit to S
}
Spade::Card sp; // allows access to functions in Card
string Spade::Description() const // Outputs card characteristics - value and color and suit as a string
{
int Sval = Card::GetValue();
string Scol = Card::GetColor();
char Sst = Card::GetSuit();
string d = "Value = "; // temporary variable used to accumulate result
switch (Sval) // Append card value to variable's value
{
case 2: d = d + "2"; break; // Number cards
case 3: d = d + "3"; break;
case 4: d = d + "4"; break;
case 5: d = d + "5"; break;
case 6: d = d + "6"; break;
case 7: d = d + "7"; break;
case 8: d = d + "8"; break;
case 9: d = d + "9"; break;
case 10: d = d + "10"; break;
case 11: d = d + "J"; break; // Face cards
case 12: d = d + "Q"; break;
case 13: d = d + "K"; break;
case 14: d = d + "A"; break;
default: d = d + "?"; break; // Unknown card
}
d = d + ", Color = "; // adds color to output string
if (Scol=="black") d = d + "black";
if (Scol=="red") d = d + "red";
else d=+ "unknown";
// appends suit to output string
d =+ ", Suit = ";
switch (Sst)
{
case 'H': d =+ "H"; break;
case 'C': d =+ 'C'; break;
case 'D': d =+ 'D'; break;
case 'U': d =+ 'U'; break;
}
return d; // Return string describing card value
}

26
CPE212/Project_02/spade.h Normal file
View File

@ -0,0 +1,26 @@
//
// spade.h -- CPE 212-01, Fall 2010 -- Project02 -- Classes
//
// DO NOT MODIFY OR SUBMIT THIS FILE!!!
//
#ifndef SPADE_H
#define SPADE_H
#include "blackcard.h"
class Spade : public BlackCard
{
private:
// No additional private members
public:
// Constructors
Spade(int v); // Creates a black spade card with value v
string Description() const; // Outputs card characteristics - value, color, suit
// Hint: use base class Description method to generate part of
// the description and append the suit information at the end
};
#endif

BIN
CPE212/Project_02/spade.o Normal file

Binary file not shown.

212
CPE212/Project_03/main.cpp Normal file
View File

@ -0,0 +1,212 @@
//
// main.cpp -- 2010 Fall -- Project03 -- Stacks
//
// Driver program for Stack ADT -- The text files (read by this code) contain a series of commands
// that will help you test your Stack ADT code by triggering various Stack class methods.
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#include <iostream>
#include <fstream>
#include <new>
#include <cstddef>
#include "stack.h"
using namespace std;
int main(int argc, char* argv[])
{
ifstream inputs; // Input file for commands
char op; // Hold operation and optional char input
int value; // Value input from file
string comment; // Holds comment from file
Stack* sPtr = NULL; // Will point to TemplateQ object
// Output usage message if one input file name is not provided
if (argc != 2)
{
cout << "Usage:\n project03 <inputfile>\n";
return 1;
}
// Attempt to open input file -- terminate if file does not open
inputs.open(argv[1]);
if (!inputs)
{
cout << "Error - unable to open input file" << endl;
return 1;
}
// Input and echo header comment from file
getline(inputs, comment);
cout << endl << '#' << comment << endl;
// Process commands from input file
inputs >> op; // Attempt to input first command
while (inputs)
{
switch (op) // Process operation input from file
{
case '#': // Test file comment
getline(inputs, comment); // Input and echo the comment appearing in the test file
cout << '#' << comment << endl;
break;
case 'c': // Parameterized Constructor
inputs >> value;
cout << endl << "Stack(" << value << ")";
try
{
sPtr = new Stack(value); // Attempt to create a stack object with array size value
cout << " -- Successful" << endl;
}
catch ( std::bad_alloc )
{
cout << "Failed : Terminating now..." << endl;
return 1;
}
break;
case '+': // Push
inputs >> value;
cout << "Push(" << value << ")";
try
{
sPtr->Push(value);
cout << " -- successful";
}
catch (StackFull)
{
cout << " -- Failed Full Stack";
}
cout << endl;
break;
case '-': // Pop
cout << "Pop() -- ";
try
{
sPtr->Pop();
cout << "successful";
}
catch (StackEmpty)
{
cout << "Failed Empty Stack";
}
cout << endl;
break;
case 'f': // IsFull
cout << "IsFull() -- ";
try
{
if (sPtr->IsFull())
cout << "true";
else
cout << "false";
}
catch ( ... )
{
cout << "operation failed";
}
cout << endl;
break;
case 'e': // IsEmpty
cout << "IsEmpty() -- ";
try
{
if (sPtr->IsEmpty())
cout << "true";
else
cout << "false";
}
catch ( ... )
{
cout << "operation failed";
}
cout << endl;
break;
case 'm': // Make Empty
sPtr->MakeEmpty();
cout << "MakeEmpty()" << endl;
break;
case 'p': // Print Stack
cout << "Print() -- ";
sPtr->Print();
break;
case 't': // Top of Stack
try
{
cout << "Top() -- " << sPtr->Top() << endl;
}
catch (StackEmpty)
{
cout << "Top() -- Failed Empty Stack" << endl;
}
break;
case '>': // Max value within Stack
try
{
cout << "Max() -- " << sPtr->Max() << endl;
}
catch (StackEmpty)
{
cout << "Max() -- Failed Empty Stack" << endl;
}
break;
case '<': // Min value within Stack
try
{
cout << "Min() -- " << sPtr->Min() << endl;
}
catch (StackEmpty)
{
cout << "Min() -- Failed Empty Stack" << endl;
}
break;
case '?': // Peek(n) Stack
inputs >> value;
try
{
cout << "Peek(" << value << ") -- " << sPtr->Peek(value) << endl;
}
catch (StackInvalidPeek)
{
cout << "Peek(" << value << ") -- Failed Invalid Peek" << endl;
}
break;
case 's': // Size of Stack
cout << "Size() -- " << sPtr->Size() << endl;
break;
case 'z': // Capacity of Stack
cout << "Capacity() -- " << sPtr->Capacity() << endl;
break;
case 'd': // Destructor
delete sPtr;
sPtr = NULL;
cout << "~Stack()" << endl << endl;
break;
default: // Error
cout << "Error - unrecognized operation '" << op << "'" << endl;
cout << "Terminating now..." << endl;
return 1;
break;
}
inputs >> op; // Attempt to input next command
}
return 0;
} // End main()

BIN
CPE212/Project_03/main.o Normal file

Binary file not shown.

View File

@ -0,0 +1,15 @@
# Project03 makefile
project03: stack.o main.o
g++ stack.o main.o -o project03
stack.o: stack.h stack.cpp
g++ -c stack.cpp
main.o: stack.h main.cpp
g++ -c main.cpp
clean:
rm *.o project03

View File

@ -0,0 +1,43 @@
# p03input1.txt -- Test: Stack(), Push(), Pop(), and Top()
c 8
p
t
+ 5
+ 10
+ 15
p
t
+ 20
+ 25
+ 30
p
t
-
-
p
+ 35
+ 40
t
+ 45
t
p
-
-
-
-
-
-
-
-
p
t
d
c 4
p
-
t
d

View File

@ -0,0 +1,38 @@
# p03input2.txt -- Test IsFull(), IsEmpty(), and MakeEmpty()
c 8
e
f
+ 5
+ 10
+ 15
+ 20
+ 25
+ 30
p
e
f
m
p
e
f
+ 35
+ 40
+ 45
+ 50
p
e
f
-
-
-
p
e
f
m
p
e
f
d

View File

@ -0,0 +1,58 @@
# p03input3.txt -- Test Size(), Capacity()
# Test Size()
c 6
p
s
+ 5
+ 10
p
s
+ 15
+ 20
p
s
+ 25
+ 30
p
s
-
-
-
p
s
-
-
-
p
s
d
# Test Capacity()
c 2
z
+ 5
z
+ 10
z
+ 15
z
+ 20
z
+ 25
z
+ 30
z
p
-
-
-
z
p
-
-
-
z
p
d

View File

@ -0,0 +1,34 @@
# p03input4.txt -- Test Min() and Max()
c 8
<
>
+ 5
+ 30
+ 15
+ 20
+ 50
+ 10
p
<
>
+ 20
+ 50
+ 5
p
<
>
-
-
-
p
<
>
-
-
-
p
<
>
d

View File

@ -0,0 +1,51 @@
# p03input5.txt -- Test Peek(n)
c 8
? 0
+ 5
+ 30
+ 15
+ 20
+ 50
+ 10
p
? 0
? 1
? 2
? 3
? 4
? 5
? 6
p
-
-
-
p
? 0
? 1
? 2
? 5
p
-
-
-
p
? 0
? 1
? 2
? 3
? 4
? 5
+ 25
+ 9
+ 8
p
? 0
? 1
? 2
? 3
? 4
? 5
d

BIN
CPE212/Project_03/project03 Normal file

Binary file not shown.

157
CPE212/Project_03/stack.cpp Normal file
View File

@ -0,0 +1,157 @@
#include <iostream>
#include <new>
#include "stack.h"
int Max_Stack; // Global variable for stack size
Stack::Stack(int n) // Parameterized constructor dynamically allocates an empty stack array
{ // that may hold no more than n elements and initializes other private variables
Max_Stack=n;
array = new int[n];
top=-1;
num=n;
}
void Stack::Resize(int n) // Attempts to increase size of stack array to 2*num and then push n onto stack
{ // If unable to resize, throw StackFull exception
try
{
int largerArry[2*Max_Stack];
for (int i = 0; i < num; i++)
{
largerArry[i]=array[i];
}
delete [] array;
num= num * 2; // num to twice original size
Max_Stack=num;
array = largerArry;
array[top]=n;
//top++;
}
catch( ... )
{
throw StackFull();
//return;
}
}
Stack::~Stack()
{
delete [] array;
}
void Stack::Push(int n)
{
bool full = IsFull();
if (full)
{
Resize(n);
array[top]=n;
}
//array[top]=n;
top++;
array[top]=n;
}
void Stack::Pop()
{
bool empty=IsEmpty();
if (empty)
{
throw StackEmpty();
}
top--;
}
bool Stack::IsEmpty() const
{
return (top == -1);
}
bool Stack::IsFull() const
{
return (top == Max_Stack);
}
void Stack::MakeEmpty()
{
top = -1;
}
int Stack::Top() const
{
bool empty=IsEmpty();
if (empty)
{
throw StackEmpty();
//return;
}
return array[top];
}
int Stack::Size() const // Returns number of items on stack WITHOUT modifying the stack
{
return top;
}
int Stack::Max() const // Returns value of largest integer on stack WITHOUT modifying the stack
{ // If stack is empty, throws StackEmpty
bool empty=IsEmpty();
if (empty)
{
throw StackEmpty();
}
int i;
// Initialize maximum element
int max = array[0];
// Traverse array elements
// from second and compare
// every element with current max
for (i = 1; i < top; i++)
{
if (array[i] > max)
max = array[i];
}
return max;
}
int Stack::Min() const // Returns value of smallest integer on stack WITHOUT modifying the stack
{ // If stack is empty, throws StackEmpty
bool empty=IsEmpty();
if (empty)
{
throw StackEmpty();
}
int i;
// Initialize minimum element
int min = array[0];
// Traverse array elements
// from second and compare
// every element with current min
for (i = 1; i < top; i++)
{
if (array[i] < min)
min = array[i];
}
return min;
}
int Stack::Peek(unsigned int n) const // Returns stack value n levels down from top of stack. Peek(0) = Top()
{ // If position n does not exist, throws StackInvalidPeek
if(!array[top-n])
throw StackInvalidPeek();
int st=array[top-n];
return st;
}
int Stack::Capacity() const // Returns total num of elements that maybe stored in stack array
{
return Max_Stack;
}

103
CPE212/Project_03/stack.h Normal file
View File

@ -0,0 +1,103 @@
//
// stack.h 2010 Fall CPE 212 -- Project03 -- Stacks
//
// The comments have been updated, but there have been no changes to the code.
//
// Specification file for Stack class, a stack of integers implemented
// as a linked list of nodes.
//
// ***** DO NOT MODIFY OR SUBMIT THIS FILE *****
//
#include <iostream>
using namespace std;
#ifndef STACK_H
#define STACK_H
class StackEmpty
{
// Exception class - throw an object of this type when stack is empty
// Hint: there is no code for exception classes
};
class StackFull
{
// Exception class - throw an object of this type when stack is full
};
class StackInvalidPeek
{
// Exception class - throw an object of this type when invalid peek position is used
};
class Stack // Models stack of integers ADT implemented as a dynamically allocated array
{
private:
int* array; // Points to the stack array
int num; // Holds max number of elements that may be stored in stack array
int top; // Holds the index of the top data value stored on the stack
void Resize(int n); // Attempts to increase size of stack array to 2*num and then push n onto stack
// If unable to resize, throw StackFull exception
public:
Stack(int n); // Parameterized constructor dynamically allocates an empty stack array
// that may hold no more than n elements and initializes other private variables
~Stack(); // Destructor deallocates all dynamically-allocated memory
// associated with the object
void Push(int n); // Pushes integer n onto top of stack. If stack is full, attempts to
// resize stack and then push n. If unable to resize, throws StackFull exception.
void Pop(); // Removes top integer from stack
// If stack is empty, throws StackEmpty exception
bool IsEmpty() const; // Returns true if stack is empty; false otherwise
bool IsFull() const; // Returns true if stack is full; false otherwise
void MakeEmpty(); // Removes all items from stack leaving an empty, but usable stack with capacity num
// If stack is already empty, MakeEmpty() does nothing
int Top() const; // Returns value of top integer on stack WITHOUT modifying the stack
// If stack is empty, throws StackEmpty exception
int Size() const; // Returns number of items on stack WITHOUT modifying the stack
int Max() const; // Returns value of largest integer on stack WITHOUT modifying the stack
// If stack is empty, throws StackEmpty
int Min() const; // Returns value of smallest integer on stack WITHOUT modifying the stack
// If stack is empty, throws StackEmpty
int Peek(unsigned int n) const; // Returns stack value n levels down from top of stack. Peek(0) = Top()
// If position n does not exist, throws StackInvalidPeek
int Capacity() const; // Returns total num of elements that maybe stored in stack array
/******* DO NOT MODIFY ANY OF THE CODE FOR PRINT() *******/
/****** DO NOT PLACE A COPY OF PRINT() CODE IN STACK.CPP!!! *******/
void Print() const // Writes stack contents to stdout, separated by a space, followed by endl
{
int index = top;
cout << "Top { ";
while (index != -1) // Loop to output any values stored on stack
{
cout << array[index] << " ";
index--;
}
cout << "} Bottom" << endl;
} // End Print()
}; // End Class Stack
#endif

BIN
CPE212/Project_03/stack.o Normal file

Binary file not shown.

154
CPE212/Project_04/list.cpp Normal file
View File

@ -0,0 +1,154 @@
#include <iostream>
#include <new>
#include "list.h"
Node list;
List::List()
{
head = NULL;
num=0;
}
List::~List()
{
delete head;
}
void List::Append(string newword)
{
Node* tempPtr=new Node;
tempPtr->word= newword;
tempPtr->next= NULL;
//num++;
if (head==NULL)
{
head=tempPtr;
num++;
return;
//head->next=NULL;
}
else
{
Node *current=head;
while(current ->next) current=current->next;
current->next = tempPtr;
}
num++;
}
void List::InsertAt(int pos, string newword)
{
Node* prev = new Node();
Node* curr = new Node();
Node* newNode = new Node();
newNode->word = newword;
int tempPos = 0; // Traverses through the list
curr = head; // Initialize current to head;
if(head != NULL)
{
while(curr->next != NULL && tempPos != pos)
{
prev = curr;
curr = curr->next;
tempPos++;
}
if(pos==0)
{
}
else if(curr->next == NULL && pos == tempPos+1)
{
Append(newword);
// Call function to append
}
else if(pos > tempPos+1 || pos>num || pos<0) throw ListBadPosition();
//Position not valid
else
{
prev->next = newNode;
newNode->next = curr;
}
}
else
{
head = newNode;
newNode->next=NULL;
}
}
void List::Delete(string someword)
{
Node *prev=head;
Node *current=head->next;
int wordNotFound=0;
while (current != NULL)
{
// If current word is in list, break out of loop
if(current->word == someword) break;
else
{
prev=current;
prev=current->next;
}
}
if(current==NULL) throw ListNotFound();
// Error handling: if current word is not in list, throw ListNotFound
else
{
prev->next = current ->next;
delete current;
}
}
void List::Replace(string oldword, string newword)
{
Node *current=head;
int oldWordNotFound=0;
while (current != NULL)
{
// if oldword is found in list, replace oldword with newword
if(current->word==oldword)
{
current->word = newword;
return;
}
// if oldword not= to current word, increment wordNotFound
oldWordNotFound++;
current = current -> next;
if(oldWordNotFound==num)
break;
}
// if oldWordNotFound==num, throw ListNotFound
throw ListNotFound();
}
int List::Length() const
{
return num;
}
bool List::Find(string someword) const
{
Node *current=head;
int wordNotFound=0;
while (current != NULL)
{
// if current word does not equal someword, increment wordNotFound
if(current->word != someword)
{
wordNotFound++;
}
// If current word is in list, return true
if(current->word == someword) return true;
current = current->next;
}
// if wordNotFound == num, return false
if(wordNotFound == num) return false;
}

101
CPE212/Project_04/list.h Normal file
View File

@ -0,0 +1,101 @@
//
// list.h -- 2010 Fall CPE 212 -- Project04 -- Lists
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#ifndef LIST_H
#define LIST_H
#include <iostream>
using namespace std;
class ListEmpty { /*** Empty Error Class ***/ };
class ListFull { /*** Empty Error Class ***/ };
class ListNotFound { /*** Empty Error Class ***/ };
class ListBadPosition { /*** Empty Error Class ***/ };
struct Node
{
string word; // A word in a phrase
Node* next; // Pointer to next node in sequence
};
class List // List ADT used to store words in a phrase
{
private:
Node* head; // Pointer to head of word list
int num; // Number of words stored in list
public:
/***** Constructor and Destructor *****/
List();
// Description of List()
// Constructor sets state of list to empty
~List();
// Description of ~List()
// Destructor must deallocate all list nodes
/***** Transformer Methods *****/
void Append(string newword);
// Description of Append(...)
// Appends newword to the end of the current phrase
// Error Handling: If list is full, throw ListFull object.
void InsertAt(int pos, string newword);
// Description of InsertAt(...)
// Inserts newword at position pos.
// Positions numbered starting with zero (0 <= pos <= num).
// Hint: pos == num ==> append
// Word previously at pos should now be at position pos+1
// Error Handling: If list is full, throws ListFull object
// If pos out of range, throws ListBadPosition object
void Delete(string someword);
// Description of Delete(...)
// Deletes the first instance of someword if it is present.
// Error Handling: If someword is not in list, throws ListNotFound object
void Replace(string oldword, string newword);
// Description of Replace(...)
// Replaces the first instance of oldword with newword.
// Error Handling: If oldword not found, throws ListNotFound object
/***** Observer Methods *****/
int Length() const;
// Description of Length()
// Returns number of words in the list
// Error Handling: none
bool Find(string someword) const;
// Description of Find(...)
// Returns true if someword is in list, false otherwise
// Error Handling: none
// DO NOT MODIFY OR SUBMIT Print()
void Print() const
// Description of Print()
// Prints the entire phrase to stdout
{
Node* temp = head; // Temp variable for scanning through list starting at head
cout << "Head {"; // Output open brace
while (temp != NULL) // While there are words that must be printed...
{
cout << ' ' << temp->word; // ... print the next word
temp = temp->next; // ... and advance to the next node.
}
cout << " }"; // Output close brace
}
};
#endif

BIN
CPE212/Project_04/list.o Normal file

Binary file not shown.

168
CPE212/Project_04/main.cpp Normal file
View File

@ -0,0 +1,168 @@
//
// main.cpp -- 2010 Fall -- Project04 -- Lists
//
// Driver program for List ADT -- The text files (read by this code) contain a series of commands
// that will help you test your List ADT code by triggering various List class methods.
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#include <iostream>
#include <fstream>
#include <new>
#include <cstddef>
#include "list.h"
using namespace std;
int main(int argc, char* argv[])
{
ifstream inputs; // Input file for commands
char op; // Hold operation and optional char input
string value, value2; // Values input from file
string comment; // Holds comment from file
int pos; // Holds position value from file
List* ptr = NULL; // Will point to List object
// Output usage message if one input file name is not provided
if (argc != 2)
{
cout << "Usage:\n project04 <inputfile>\n";
return 1;
}
// Attempt to open input file -- terminate if file does not open
inputs.open(argv[1]);
if (!inputs)
{
cout << "Error - unable to open input file" << endl;
return 1;
}
// Input and echo header comment from file
getline(inputs, comment); // Input and echo the comment appearing in the test file
cout << endl << '#' << comment << endl << endl;
// Process commands from input file
inputs >> op; // Attempt to input first command
while (inputs)
{
switch (op) // Process operation input from file
{
case '#': // Test file comment
getline(inputs, comment); // Input and echo the comment appearing in the test file
cout << '#' << comment << endl;
break;
case 'c': // Parameterized Constructor
cout << endl << "List()";
try
{
ptr = new List(); // Attempt to create a List object
cout << " -- Successful" << endl;
}
catch ( std::bad_alloc )
{
cout << "Failed : Terminating now..." << endl;
return 1;
}
break;
case 'a': // Append
inputs >> value;
cout << "Append(" << value << ")";
try
{
ptr->Append(value);
cout << " -- successful";
}
catch (ListFull)
{
cout << " -- Failed Full List";
}
cout << endl;
break;
case '-': // Delete word
inputs >> value;
cout << "Delete(" << value << ") -- ";
try
{
ptr->Delete(value);
cout << "successful";
}
catch (ListNotFound)
{
cout << "Failed Not In List";
}
cout << endl;
break;
case '+': // Insert at position
inputs >> pos >> value;
cout << "InsertAt(" << pos << ", " << value << ") -- ";
try
{
ptr->InsertAt(pos, value);
cout << "Successful" << endl;
}
catch (ListBadPosition)
{
cout << "Failed Bad Position" << endl;
}
break;
case 'p': // Print List
cout << "Print() -- ";
ptr->Print();
cout << endl;
break;
case 'r': // Replace word
inputs >> value >> value2;
try
{
cout << "Replace(" << value << ", " << value2 << ") -- ";
ptr->Replace(value, value2);
cout << "Successful" << endl;
}
catch (ListNotFound)
{
cout << "Failed Not Found in List" << endl;
}
break;
case '?': // Find in List
inputs >> value;
if ( ptr->Find(value) )
{
cout << "Find(" << value << ") -- True" << endl;
}
else
{
cout << "Find(" << value << ") -- False" << endl;
}
break;
case 'l': // Length of List
cout << "Length() -- " << ptr->Length() << endl;
break;
case 'd': // Destructor
delete ptr;
ptr = NULL;
cout << "~List()" << endl << endl;
break;
default: // Error
cout << "Error - unrecognized operation '" << op << "'" << endl;
cout << "Terminating now..." << endl;
return 1;
break;
}
inputs >> op; // Attempt to input next command
}
return 0;
} // End main()

BIN
CPE212/Project_04/main.o Normal file

Binary file not shown.

View File

@ -0,0 +1,15 @@
# Project04 makefile
project04: list.o main.o
g++ list.o main.o -o project04
list.o: list.h list.cpp
g++ -c list.cpp
main.o: list.h main.cpp
g++ -c main.cpp
clean:
rm *.o project04

View File

@ -0,0 +1,38 @@
# p04input1.txt -- Test List(), ~List(), Length(), Append()
# Test Append()
c
p
a See
p
a Spot
p
a run
p
d
# Test Length()
c
l
p
a Observe
l
p
a Spot
l
p
a running
l
p
a swiftly
l
p
a away
l
p
d

View File

@ -0,0 +1,44 @@
# p04input2.txt -- Test List(), ~List(), Append(), Find()
# Test successful find
c
p
a See
p
a Spot
p
a run
p
? See
p
? Spot
p
? run
p
d
# Test unsuccessful find
c
p
a Observe
p
a Spot
p
a running
p
a swiftly
p
a away
p
? slowly
p
? run
p
? spot
p
d

View File

@ -0,0 +1,51 @@
# p04input3.txt -- Test List(), ~List(), Delete()
# Test successful delete
c
p
a See
p
a Spot
p
a run
p
a swiftly
p
a away
p
- run
p
- Spot
p
- See
p
- away
p
- swiftly
p
d
# Test unsuccessful delete
c
p
a See
p
a Spot
p
a run
p
a slowly
p
a away
p
- Observe
p
- spot
p
d

View File

@ -0,0 +1,38 @@
# p04input4.txt -- Test Replace()
# Test successful replace
c
p
a See
p
a Spot
p
a run
p
p
r run walk
p
r See Observe
p
r Spot Dot
p
d
# Test unsuccessful replace
c
a See
a Spot
a run
a swiftly
a away
p
r spot goat
p
r goat boat
p
d

View File

@ -0,0 +1,31 @@
# p04input5.txt -- Test InsertAt()
# Test successful InsertAt
c
a See
a Spot
a run
p
+ 0 Zero
p
+ 1 One
p
+ 4 Four
p
+ 5 Five
p
+ 7 Seven
p
# Test unsuccessful InsertAt
+ -1 Bad
p
+ 10 Ten
p
+ 20 Twenty
p
d

BIN
CPE212/Project_04/project04 Normal file

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,329 @@
#include <iostream>
#include <new>
#include "bstree.h"
template <typename SomeType>
BSTree<SomeType>::BSTree()
{
BSTreeNode<SomeType>* rootPtr = NULL;
}
template <typename SomeType>
// start of Delete(...)
// Recursive function that traverses the tree starting at treePtr to locate the data value to be removed
// Once located, DeleteNode is invoked to remove the value from the tree
// If tree is not empty and item is NOT present, throw NotFoundBSTree
void BSTree<SomeType>::Delete(BSTreeNode<SomeType>*& treePtr, SomeType& item)
{
if(item < treePtr->data)
Delete(treePtr->leftPtr, item); // Look in left subtree
else if(item > treePtr->data)
Delete(treePtr->rightPtr, item); // Look in right subtree
else if (treePtr->data == item)
DeleteNode(treePtr); // Node found; call DeleteNode
else
NotFoundBSTree();
}
template <typename SomeType>
void BSTree<SomeType>::DeleteNode(BSTreeNode<SomeType>*& treePtr)
// start of DeleteNode()
// Removes the node pointed to by treePtr from the tree
// Hint: calls GetPredecessor and Delete
{
SomeType data;
BSTreeNode<SomeType>* tempPtr;
if (treePtr->leftPtr==NULL)
{
treePtr=treePtr->rightPtr;
delete tempPtr;
}
else if (treePtr->rightPtr==NULL)
{
treePtr = treePtr->leftPtr;
delete tempPtr;
}
else
{
GetPredecessor(treePtr->leftPtr);
treePtr->data = data;
Delete(treePtr->leftPtr, data);
}
} // end of DeleteNode(...)
template <typename SomeType>
void BSTree<SomeType>::Insert(BSTreeNode<SomeType>*& ptr, SomeType item)
// Start of Insert(...)
// Recursive function that finds the correct position of item and adds it to the tree
// Throws FoundInBSTree if item is already in the tree
{
if (ptr==NULL)
{
ptr = new BSTreeNode<SomeType>;
ptr->rightPtr = NULL;
ptr->leftPtr = NULL;
ptr->data = item;
}
else if (item < ptr->data)
Insert(ptr->leftPtr, item);
else
Insert(ptr->rightPtr, item);
//else if (ptr->data == item) FoundInBSTree();
}
template <typename SomeType>
void BSTree<SomeType>::Destroy(BSTreeNode<SomeType>*& ptr)
// Destroy()
// Recursively deallocates every node in the tree pointed to by ptr
{
if (&ptr==NULL)
{
Destroy(ptr->leftPtr);
Destroy(ptr->rightPtr);
delete ptr;
}
} // end of Destroy()
template <typename SomeType>
void BSTree<SomeType>::CopyTree(BSTreeNode<SomeType>*& copy, const BSTreeNode<SomeType>* originalTree)
// CopyTree()
// Recursively copies all data from original tree into copy
{
if (originalTree == NULL)
copy = NULL;
else
{
copy = new BSTreeNode<SomeType>;
copy->data = originalTree->data;
CopyTree(copy->leftPtr, originalTree->leftPtr);
CopyTree(copy->rightPtr, originalTree->rightPtr);
}
}
template <typename SomeType>
SomeType BSTree<SomeType>::GetPredecessor(BSTreeNode<SomeType>* treePtr) const
// GetPredecessor()
// Finds the largest data value in the tree pointed to by treePtr and returns that data value
// as the functions return value
{
while (treePtr->rightPtr != NULL)
treePtr = treePtr->rightPtr;
return (treePtr->data);
}
template <typename SomeType>
int BSTree<SomeType>::CountNodes(BSTreeNode<SomeType>* treePtr) const
// CountNodes()
// Recursive function that counts every node in the tree pointed to by treePtr and returns the
// count as the function return value
{
if (&treePtr == NULL)
return 0;
else
return CountNodes(treePtr->leftPtr) + CountNodes(treePtr->rightPtr) + 1;
}
template <typename SomeType>
int BSTree<SomeType>::LevelCount(BSTreeNode<SomeType>* treePtr) const
// LevelCount()
// Recursive function that traverses the entire tree to determine the total number of levels in the tree
{
if(treePtr->leftPtr == NULL && treePtr->rightPtr == NULL)
return 0;
int left = 0;
if (treePtr->leftPtr != NULL)
left = LevelCount(treePtr->leftPtr);
int right = 0;
if (treePtr->rightPtr != NULL)
right = LevelCount(treePtr->rightPtr);
return (max(left, right) + 1);
}
template <typename SomeType>
int BSTree<SomeType>::FindLevel(BSTreeNode<SomeType>* treePtr, SomeType item) const
// FindLevel()
// Recursive function that traverses the tree looking for item and returns the level where
// item was found
{
int static level = 0;
// if (treePtr == NULL)
// return 0;
// int left = 0;
// if (treePtr->leftPtr != NULL && item != treePtr->data)
// left = LevelCount(treePtr->leftPtr);
// int right = 0;
// if (treePtr->rightPtr != NULL)
// right = LevelCount(treePtr->rightPtr);
// return (max(left, right));
}
template <typename SomeType>
//start of BSTree(...)
BSTree<SomeType>::BSTree(const BSTree<SomeType>& someTree)
// BSTree()
// Copy constructor for BSTree
// Hint: calls CopyTree
{
if (someTree.rootPtr==NULL)
{
rootPtr=NULL;
}
else
CopyTree(this->rootPtr, someTree.rootPtr);
}
template <typename SomeType>
void BSTree<SomeType>::operator=(const BSTree<SomeType>& originalTree)
// operator=()
// Overloaded assignment operator for BSTree.
// Hint: calls CopyTree
{
if (&originalTree == this)
return;
Destroy(rootPtr);
CopyTree(rootPtr, originalTree.rootPtr);
}
template <typename SomeType>
BSTree<SomeType>::~BSTree()
// ~BSTree()
// Destructor deallocates all tree nodes
// Hint: calls the private helper function Destroy
{
Destroy(rootPtr);
}
template <typename SomeType>
void BSTree<SomeType>::InsertItem(SomeType item)
// InsertItem()
// Inserts item into BSTree; if tree already full, throws FullBSTree exception
// If item is already in BSTree, throw FoundInBSTree exception
// Hint: calls the private helper function Insert
{
Insert(rootPtr,item);
}
template <typename SomeType>
SomeType BSTree<SomeType>::DeleteItem(SomeType item)
// DeleteItem()
// Deletes item from BSTree if item is present AND returns object via function return value
// If tree is empty, throw the EmptyBSTree exception
// If tree is not empty and item is NOT present, throw NotFoundBSTree
// Hint: calls the private helper function Delete
{
//if (&rootPtr == NULL) EmptyBSTree();
if (IsEmpty())
throw EmptyBSTree();
else
SomeType itemCopy = item; // Make an copy for item
Delete(rootPtr, item); // Delete item in tree
// return itemCopy;
}
template <typename SomeType>
void BSTree<SomeType>::MakeEmpty()
// MakeEmpty()
// Deallocates all BSTree nodes and sets root pointer to NULL
// Hint: calls the private helper function Destroy
{
Destroy(rootPtr);
rootPtr=NULL;
}
template <typename SomeType>
int BSTree<SomeType>::Size() const
// Size()
// Returns total number of data values stored in tree
{
return CountNodes(rootPtr);
}
template <typename SomeType>
bool BSTree<SomeType>::IsFull() const
{
BSTreeNode<SomeType>* location;
try
{
location = new BSTreeNode<SomeType>;
delete location;
return false;
}
catch( bad_alloc )
{
return true;
}
}
template <typename SomeType>
bool BSTree<SomeType>::IsEmpty() const
{
if (rootPtr == NULL) return true;
return false;
}
template <typename SomeType>
SomeType BSTree<SomeType>::Min() const
{
// if (rootPtr == NULL) EmptyBSTree();
// BSTreeNode<SomeType>* current;
// &current = rootPtr;
// while (current > current->data != NULL)
// {
// current = current->leftPtr;
// }
// return(current->leftPtr);
}
template <typename SomeType>
SomeType BSTree<SomeType>::Max() const
{
// if (rootPtr == NULL) EmptyBSTree();
// BSTreeNode<SomeType>* current;
// current = rootPtr;
// while (current > current->data != NULL)
// {
// current = current->rightPtr;
// }
// return(&current->rightPtr);
}
template <typename SomeType>
int BSTree<SomeType>::TotalLevels() const
// TotalLevels()
// Returns the maximum level value for current tree contents
// Levels are numbered 0, 1, ..., N-1. This function returns N
// Throws EmptyBSTree if empty
// Hint: calls the private helper function LevelCount
{
if (&rootPtr == NULL) EmptyBSTree();
int level = LevelCount(rootPtr);
return level+1;
}
template <typename SomeType>
int BSTree<SomeType>::Level(SomeType item) const
// Level()
// Returns the level within the BSTree at which the value item is found
// If tree is empty, throws EmptyBSTree
// If tree is not empty and item is not found, throws NotFoundBSTree
// Hint: calls the private helper funtion FindLevel
{
if (rootPtr == NULL) EmptyBSTree();
return FindLevel(rootPtr, item);
}

View File

@ -0,0 +1,316 @@
#include <iostream>
#include <new>
#include "bstree.h"
template <typename SomeType>
// start of Delete(...)
// Recursive function that traverses the tree starting at treePtr to locate the data value to be removed
// Once located, DeleteNode is invoked to remove the value from the tree
// If tree is not empty and item is NOT present, throw NotFoundBSTree
void BSTree<SomeType>::Delete(BSTreeNode<SomeType>*& treePtr, SomeType& item)
{
if(item < treePtr->data)
Delete(treePtr->leftPtr, item); // Look in left subtree
else if(item > treePtr->data)
Delete(treePtr->rightPtr, item); // Look in right subtree
else if (treePtr == item)
DeleteNode(treePtr); // Node found; call DeleteNode
else
NotFoundBSTree();
}
template <typename SomeType>
void BSTree<SomeType>::DeleteNode(BSTreeNode<SomeType>*& treePtr)
// start of DeleteNode()
// Removes the node pointed to by treePtr from the tree
// Hint: calls GetPredecessor and Delete
{
SomeType data;
BSTreeNode<SomeType>* tempPtr;
if (treePtr->leftPtr==NULL)
{
treePtr=treePtr->rightPtr;
delete tempPtr;
}
else if (treePtr->rightPtr==NULL)
{
treePtr = treePtr->leftPtr;
delete tempPtr;
}
else
{
GetPredecessor(treePtr->leftPtr, data);
treePtr->data = data;
Delete(treePtr->leftPtr, data);
}
} // end of DeleteNode(...)
template <typename SomeType>
void BSTree<SomeType>::Insert(BSTreeNode<SomeType>*& ptr, SomeType item)
// Start of Insert(...)
// Recursive function that finds the correct position of item and adds it to the tree
// Throws FoundInBSTree if item is already in the tree
{
if (ptr == item) FoundInBSTree();
if (ptr==NULL)
{
ptr = new BSTreeNode<SomeType>;
ptr->rightPtr = NULL;
ptr->leftPtr = NULL;
ptr->data = item;
}
else if (item < ptr->data)
Insert(ptr->leftPtr, item);
else
Insert(item->rightptr, item);
if (ptr ==item) FoundInBSTree();
}
template <typename SomeType>
void BSTree<SomeType>::Destroy(BSTreeNode<SomeType>*& ptr)
// Destroy()
// Recursively deallocates every node in the tree pointed to by ptr
{
if (ptr==NULL)
{
Destroy(ptr->leftPtr);
Destroy(ptr->rightPtr);
delete ptr;
}
} // end of Destroy()
template <typename SomeType>
void BSTree<SomeType>::CopyTree(BSTreeNode<SomeType>*& copy, const BSTreeNode<SomeType>* originalTree)
// CopyTree()
// Recursively copies all data from original tree into copy
{
if (originalTree == NULL)
copy = NULL;
else
{
copy = new BSTreeNode<typename SomeType>;
copy->data = originalTree->data;
CopyTree(copy->leftPtr, originalTree->leftPtr);
CopyTree(copy->rightPtr, originalTree->rightPtr);
}
}
template <typename SomeType>
SomeType BSTree<SomeType>::GetPredecessor(BSTreeNode<SomeType>* treePtr) const
// GetPredecessor()
// Finds the largest data value in the tree pointed to by treePtr and returns that data value
// as the functions return value
{
while (treePtr->rightPtr != NULL)
treePtr = treePtr->rightPtr;
data = treePtr->data;
}
template <typename SomeType>
int BSTree<SomeType>::CountNodes(BSTreeNode<SomeType>* treePtr) const
// CountNodes()
// Recursive function that counts every node in the tree pointed to by treePtr and returns the
// count as the function return value
{
if (treePtr == NULL)
return 0;
else
return CountNodes(treePtr->leftPtr) + CountNodes(treePtr->rightPtr) + 1;
}
template <typename SomeType>
int BSTree<SomeType>::LevelCount(BSTreeNode<SomeType>* treePtr) const
// LevelCount()
// Recursive function that traverses the entire tree to determine the total number of levels in the tree
{
if(treePtr->leftPtr == NULL && treePtr->rightPtr == NULL)
return 0;
int left = 0;
if (treePtr->leftPtr != NULL)
left = LevelCount(treePtr->leftPtr);
int right = 0;
if (treePtr->rightPtr != NULL)
right = LevelCount(treePtr->rightPtr);
return (max(left, right) + 1);
}
template <typename SomeType>
int BSTree<SomeType>::FindLevel(BSTreeNode<SomeType>* treePtr, SomeType item) const
// FindLevel()
// Recursive function that traverses the tree looking for item and returns the level where
// item was found
{
int static level = 0;
if (treePtr == NULL)
return 0;
int left = 0;
if (treePtr->leftPtr != NULL && treePtr->data != item)
left = LevelCount(treePtr->leftPtr);
int right = 0;
if (treePtr->rightPtr != NULL)
right = LevelCount(treePtr->rightPtr);
return (max(left, right));
}
template <typename SomeType>
BSTree<SomeType>::BSTree()
{
rootPtr=NULL;
}
template <typename SomeType>
//start of BSTree(...)
BSTree<SomeType>::BSTree(const BSTree<SomeType>& someTree)
// BSTree()
// Copy constructor for BSTree
// Hint: calls CopyTree
{
CopyTree(someTree);
}
template <typename SomeType>
void BSTree<SomeType>::operator=(const BSTree<SomeType>& originalTree)
// operator=()
// Overloaded assignment operator for BSTree.
// Hint: calls CopyTree
{
if (originalTree==this)
return;
Destroy(rootPtr);
CopyTree(originalTree);
}
template <typename SomeType>
BSTree<SomeType>::~BSTree()
// ~BSTree()
// Destructor deallocates all tree nodes
// Hint: calls the private helper function Destroy
{
Destroy(rootPtr);
}
template <typename SomeType>
void BSTree<SomeType>::InsertItem(SomeType item)
// InsertItem()
// Inserts item into BSTree; if tree already full, throws FullBSTree exception
// If item is already in BSTree, throw FoundInBSTree exception
// Hint: calls the private helper function Insert
{
Insert(item);
}
template <typename SomeType>
SomeType BSTree<SomeType>::DeleteItem(SomeType item)
// DeleteItem()
// Deletes item from BSTree if item is present AND returns object via function return value
// If tree is empty, throw the EmptyBSTree exception
// If tree is not empty and item is NOT present, throw NotFoundBSTree
// Hint: calls the private helper function Delete
{
if (rootPtr == NULL) EmptyBSTree();
Delete(item);
}
template <typename SomeType>
void BSTree<SomeType>::MakeEmpty()
// MakeEmpty()
// Deallocates all BSTree nodes and sets root pointer to NULL
// Hint: calls the private helper function Destroy
{
Delete(rootPtr);
rootPtr=NULL;
}
template <typename SomeType>
int BSTree<SomeType>::Size() const
// Size()
// Returns total number of data values stored in tree
{
return CountNodes(rootPtr);
}
template <typename SomeType>
bool BSTree<SomeType>::IsFull() const
{
BSTreeNode<SomeType>* location;
try
{
location = new BSTreeNode<SomeType>;
delete location;
return false;
}
catch( bad_alloc )
{
return true;
}
}
template <typename SomeType>
bool BSTree<SomeType>::IsEmpty() const
{
if (rootPtr == NULL) return true;
return false;
}
template <typename SomeType>
SomeType BSTree<SomeType>::Min() const
{
if (rootPtr == NULL) EmptyBSTree();
int res = rootPtr->data;
BSTreeNode<SomeType>* current;
while (current->leftPtr != NULL)
{
current = current->leftPtr;
}
return(current->leftPtr);
}
template <typename SomeType>
SomeType BSTree<SomeType>::Max() const
{
if (rootPtr == NULL) EmptyBSTree();
BSTreeNode<SomeType>* current;
while (current->rightPtr != NULL)
{
current = current->rightPtr;
}
return(current->rightPtr);
}
template <typename SomeType>
int BSTree<SomeType>::TotalLevels() const
// TotalLevels()
// Returns the maximum level value for current tree contents
// Levels are numbered 0, 1, ..., N-1. This function returns N
// Throws EmptyBSTree if empty
// Hint: calls the private helper function LevelCount
{
if (rootPtr == NULL) EmptyBSTree();
int level = LevelCount(rootPtr);
return level+1;
}
template <typename SomeType>
int BSTree<SomeType>::Level(SomeType item) const
// Level()
// Returns the level within the BSTree at which the value item is found
// If tree is empty, throws EmptyBSTree
// If tree is not empty and item is not found, throws NotFoundBSTree
// Hint: calls the private helper funtion FindLevel
{
if (rootPtr == NULL) EmptyBSTree();
return FindLevel(rootPtr, item);
}

187
CPE212/Project_05/bstree.h Normal file
View File

@ -0,0 +1,187 @@
//
// bstree.h 2010 Fall CPE 212 - Project05 - Binary Search Tree Template
//
// Provides a declaration of the BSTree class template.
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#ifndef BSTREE_H
#define BSTREE_H
#include <cstddef>
#include <new>
#include <string>
using namespace std;
class FullBSTree // Exception class models full BSTree condition
{
/* No code here */
};
class EmptyBSTree // Exception class models empty BSTree condition
{
/* No code here */
};
class NotFoundBSTree // Exception class models not found in BSTree condition
{
/* No code here */
};
class FoundInBSTree // Exception class models found in BSTree condition
{
/* No code here */
};
template <typename SomeType>
struct BSTreeNode // Node of BSTree
{
SomeType data; // Data stored in node
BSTreeNode<SomeType>* leftPtr; // Pointer to left subtree
BSTreeNode<SomeType>* rightPtr; // Pointer to right subtree
};
template <typename SomeType>
class BSTree // BSTree Abstract Data Type
{
private:
BSTreeNode<SomeType>* rootPtr; // Pointer to root of BSTree
/************** Start of Private Helper Functions You Must Implement ****************/
void Delete(BSTreeNode<SomeType>*& treePtr, SomeType& item);
// Delete()
// Recursive function that traverses the tree starting at treePtr to locate the data value to be removed
// Once located, DeleteNode is invoked to remove the value from the tree
// If tree is not empty and item is NOT present, throw NotFoundBSTree
void DeleteNode(BSTreeNode<SomeType>*& treePtr);
// DeleteNode()
// Removes the node pointed to by treePtr from the tree
// Hint: calls GetPredecessor and Delete
void Insert(BSTreeNode<SomeType>*& ptr, SomeType item);
// Insert()
// Recursive function that finds the correct position of item and adds it to the tree
// Throws FoundInBSTree if item is already in the tree
void Destroy(BSTreeNode<SomeType>*& ptr);
// Destroy()
// Recursively deallocates every node in the tree pointed to by ptr
void CopyTree(BSTreeNode<SomeType>*& copy, const BSTreeNode<SomeType>* originalTree);
// CopyTree()
// Recursively copies all data from original tree into copy
SomeType GetPredecessor(BSTreeNode<SomeType>* treePtr) const;
// GetPredecessor()
// Finds the largest data value in the tree pointed to by treePtr and returns that data value
// as the functions return value
int CountNodes(BSTreeNode<SomeType>* treePtr) const;
// CountNodes()
// Recursive function that counts every node in the tree pointed to by treePtr and returns the
// count as the function return value
int LevelCount(BSTreeNode<SomeType>* treePtr) const;
// LevelCount()
// Recursive function that traverses the entire tree to determine the total number of levels in the tree
int FindLevel(BSTreeNode<SomeType>* treePtr, SomeType item) const;
// FindLevel()
// Recursive function that traverses the tree looking for item and returns the level where
// item was found
/************** End of Private Helper Functions You Must Implement ****************/
public:
/************** Start of Public Interface Functions You Must Implement ****************/
BSTree();
// BSTree()
// Default constructor initializes root pointer to NULL
BSTree(const BSTree<SomeType>& someTree);
// BSTree()
// Copy constructor for BSTree
// Hint: calls CopyTree
void operator=(const BSTree<SomeType>& originalTree);
// operator=()
// Overloaded assignment operator for BSTree.
// Hint: calls CopyTree
~BSTree();
// ~BSTree()
// Destructor deallocates all tree nodes
// Hint: calls the private helper function Destroy
void InsertItem(SomeType item);
// InsertItem()
// Inserts item into BSTree; if tree already full, throws FullBSTree exception
// If item is already in BSTree, throw FoundInBSTree exception
// Hint: calls the private helper function Insert
SomeType DeleteItem(SomeType item);
// DeleteItem()
// Deletes item from BSTree if item is present AND returns object via function return value
// If tree is empty, throw the EmptyBSTree exception
// If tree is not empty and item is NOT present, throw NotFoundBSTree
// Hint: calls the private helper function Delete
void MakeEmpty();
// MakeEmpty()
// Deallocates all BSTree nodes and sets root pointer to NULL
// Hint: calls the private helper function Destroy
int Size() const;
// Size()
// Returns total number of data values stored in tree
bool IsFull() const;
// IsFull()
// Returns true if BSTree is full; returns false otherwise
bool IsEmpty() const;
// IsEmpty()
// Returns true if BSTree is empty; returns false otherwise
SomeType Min() const;
// Min()
// Returns minimum value in tree; throws EmptyBSTree if tree is empty
SomeType Max() const;
// Max()
// Returns maximum value in tree; throws EmptyBSTree if tree is empty
int TotalLevels() const;
// TotalLevels()
// Returns the maximum level value for current tree contents
// Levels are numbered 0, 1, ..., N-1. This function returns N
// Throws EmptyBSTree if empty
// Hint: calls the private helper function LevelCount
int Level(SomeType item) const;
// Level()
// Returns the level within the BSTree at which the value item is found
// If tree is empty, throws EmptyBSTree
// If tree is not empty and item is not found, throws NotFoundBSTree
// Hint: calls the private helper funtion FindLevel
/************** End of Functions You Must Implement ****************/
void Print() const; // DO NOT WRITE THIS FUNCTION
// Print()
// Prints binary search tree contents in inorder, preorder, and postorder forms
// NOTE: THIS CODE HAS BEEN INCLUDED AT THE END OF main.cpp
};
#include "bstree.cpp" // Note: Template classes cannot be compiled on their own
// since the data type argument is found in the client code.
#endif

320
CPE212/Project_05/main.cpp Normal file
View File

@ -0,0 +1,320 @@
//
// main.cpp 2010 Fall CPE 212 - Project05 - Binary Search Tree Template
//
// Driver program for BSTree ADT Template -- The text files (read by this code) contain a series
// of commands that will help you test your BSTree ADT Template code by triggering various class methods.
//
// DO NOT SUBMIT THIS FILE
//
#include <iostream>
#include <fstream>
#include <string>
#include "bstree.h"
#include "student.h"
using namespace std;
int main (int argc, char * const argv[])
{
ifstream inputs; // Input file for commands
char op, ch; // Hold operation and optional char input
BSTree<Student>* tPtr = NULL; // Will point to BSTree object
string comment;
// Output usage message if one input file name is not provided
if (argc != 2)
{
cout << "Usage:\n project05 <inputfile>\n";
return 1;
}
// Attempt to open input file -- terminate if file does not open
inputs.open(argv[1]);
if (!inputs)
{
cout << "Error - unable to open input file" << endl;
return 1;
}
// Process commands from input file
getline(inputs, comment);
cout << endl << comment << endl << endl; // Output header comment
inputs >> op; // Attempt to input first command
while (inputs)
{
// Select and perform operation input from file
switch (op)
{
case '#': // Test file comment
getline(inputs, comment);
cout << '#' << comment;
break;
case 'c': // Constructor
cout << endl << "Constructor()";
try
{
tPtr = new BSTree<Student>;
cout << endl;
}
catch ( std::bad_alloc )
{
cout << "Failed : Terminating now..." << endl;
return 1;
}
break;
case '!': // Test copy constructor
try
{
cout << endl << "*** Start Copy Constructor Test ***" << endl;
BSTree<Student> dummy = *tPtr;
Student s;
inputs >> s;
cout << "Print Copy without new value" << endl;
dummy.Print();
dummy.InsertItem(s);
cout << "Print Copy plus new value" << endl;
dummy.Print();
cout << "Print Original without new value" << endl;
tPtr->Print();
cout << "CopyConstructor -- successful" << endl;
}
catch (...)
{
cout << "CopyConstructor -- Failed: copy constructor" << endl;
}
cout << "*** End Copy Constructor Test ***" << endl;
break;
case '=': // Test overloaded assignment operator
try
{
cout << endl << "*** Start Operator= Test ***" << endl;
BSTree<Student> dummy;
dummy = *tPtr;
Student s;
inputs >> s;
cout << "Print Copy without new value" << endl;
dummy.Print();
dummy.InsertItem(s);
cout << "Print Copy plus new value" << endl;
dummy.Print();
cout << "Print Original without new value" << endl;
tPtr->Print();
cout << "Operator= -- successful" << endl;
}
catch (...)
{
cout << "Operator= -- Failed: assignment operator" << endl;
}
cout << "*** End Operator= Test ***" << endl;
break;
case '+': // InsertItem
try
{
Student s; // Create temporary object to hold student info from file
inputs >> s; // Use overloaded operator to populate temporary object
cout << "InsertItem('";
s.Print();
cout << "')";
tPtr->InsertItem(s);
}
catch (FullBSTree)
{
cout << " -- Failed Full BSTree";
}
catch (FoundInBSTree)
{
cout << " -- Failed Item Already Found In BSTree";
}
cout << endl;
break;
case '-': // DeleteItem
try
{
int id;
inputs >> id;
Student s(id, "NULL", "NULL");
cout << "DeleteItem('" << id << "') -- ";
s = tPtr->DeleteItem(s);
cout << "Deleted ";
s.Print();
}
catch (EmptyBSTree)
{
cout << " -- Failed Empty BSTree";
}
catch (NotFoundBSTree)
{
cout << " -- Failed Not Found in BSTree";
}
cout << endl;
break;
case 'p': // Print BSTree
tPtr->Print();
break;
case 's': // Size of BSTree
cout << "Size() -- " << tPtr->Size() << endl;
break;
case 'm': // Make BSTree Empty
tPtr->MakeEmpty();
cout << "MakeEmpty()"<< endl;
break;
case 'd': // Destructor
delete tPtr;
tPtr = NULL;
cout << "Destructor()" << endl << endl;
break;
case '<': // Minimum
cout << "Min() -- ";
try
{
cout << tPtr->Min() << endl;
}
catch ( EmptyBSTree )
{
cout << "Failed Empty BSTree" << endl;
}
break;
case '>': // Maximum
cout << "Max() -- ";
try
{
cout << tPtr->Max() << endl;
}
catch ( EmptyBSTree )
{
cout << "Failed Empty BSTree" << endl;
}
break;
case 'l': // Size of BSTree
try
{
cout << "TotalLevels() -- " << tPtr->TotalLevels() << endl;
}
catch ( EmptyBSTree )
{
cout << "TotalLevels() -- Failed Empty BSTree" << endl;
}
break;
case '?': // Size of BSTree
try
{
int id;
inputs >> id;
Student s(id, "NULL", "NULL");
cout << "Level('" << s << "') -- ";
cout << tPtr->Level(s) << endl;
}
catch ( EmptyBSTree )
{
cout << "Failed Empty BSTree" << endl;
}
break;
default: // Error
cout << "Error - unrecognized operation '" << op << "'" << endl;
cout << "Terminating now..." << endl;
return 1;
break;
}
inputs >> op; // Attempt to input next command
}
return 0;
}
/************** Implementation of Print() function ********************/
// DO NOT MODIFY THIS CODE
#include <queue>
// This code uses the Standard Template Libary queue class, container adapter wrapper
// that makes the deque (double-ended queue) look more like a single-ended queue.
// Note the different names used for the enqueue and dequeue operations.
template <typename SomeType>
void PreOrder(BSTreeNode<SomeType>* tree, queue<SomeType>& preorder)
// Post: preorder contains the tree items in preorder.
{
if (tree != NULL)
{
preorder.push(tree->data);
PreOrder(tree->leftPtr, preorder);
PreOrder(tree->rightPtr, preorder);
}
}
template <typename SomeType>
void InOrder(BSTreeNode<SomeType>* tree, queue<SomeType>& inorder)
// Post: inorder contains the tree items in inorder.
{
if (tree != NULL)
{
InOrder(tree->leftPtr, inorder);
inorder.push(tree->data);
InOrder(tree->rightPtr, inorder);
}
}
template <typename SomeType>
void PostOrder(BSTreeNode<SomeType>* tree, queue<SomeType>& postorder)
// Post: postorder contains the tree items in postorder.
{
if (tree != NULL)
{
PostOrder(tree->leftPtr, postorder);
PostOrder(tree->rightPtr, postorder);
postorder.push(tree->data);
}
}
template <typename SomeType>
void BSTree<SomeType>::Print() const
{
queue<SomeType> preorder, inorder, postorder;
PreOrder(rootPtr, preorder);
InOrder(rootPtr, inorder);
PostOrder(rootPtr, postorder);
cout << "Print() \n-- Inorder = { ";
while (!inorder.empty())
{
cout << inorder.front() << " ";
inorder.pop();
}
cout << "} \n-- Preorder = { ";
while (!preorder.empty())
{
cout << preorder.front() << " ";
preorder.pop();
}
cout << "} \n-- Postorder = { ";
while (!postorder.empty())
{
cout << postorder.front() << " ";
postorder.pop();
}
cout << "}" << endl;
}

BIN
CPE212/Project_05/main.o Normal file

Binary file not shown.

View File

@ -0,0 +1,19 @@
# Project06 makefile
# To disable the gcov options use a # to comment out the
# following line and uncomment the line below it
#CC = g++ -fprofile-arcs -ftest-coverage
CC = g++
project05: main.o student.o
$(CC) main.o student.o -o project05
main.o: main.cpp bstree.h
$(CC) -c main.cpp
student.o: student.cpp student.h
$(CC) -c student.cpp
clean:
rm *.o *.gcda *.gcno *.gcov project05

View File

@ -0,0 +1,68 @@
// p05input1.txt - Test BSTree(), InsertItem(), ~BSTree()
# Test creating empty binary search tree
c
p
d
# Test adding one student object to binary search tree
c
+ 5678 Washington George
p
d
# Test adding student objects pre-sorted highest to lowest id
c
+ 5678 Washington George
p
+ 1234 Jefferson Thomas
p
+ 1000 Madison James
p
+ 888 Nixon Richard
p
+ 555 Lincoln Abraham
p
d
# Test adding student objects pre-sorted lowest to highest id
c
+ 555 Lincoln Abraham
p
+ 888 Nixon Richard
p
+ 1000 Madison James
p
+ 1234 Jefferson Thomas
p
+ 5678 Washington George
p
d
# Test adding an unsorted sequence of student objects
c
+ 1234 Jefferson Thomas
p
+ 888 Nixon Richard
p
+ 5678 Washington George
p
+ 555 Lincoln Abraham
p
+ 1000 Madison James
p
d
# Test adding duplicate student object to tree
c
+ 1234 Jefferson Thomas
p
+ 1234 Jefferson Thomas
p
d

View File

@ -0,0 +1,125 @@
// p05input2.txt - Test BSTree(), InsertItem(), DeleteItem(), MakeEmpty(), ~BSTree()
# Test deleting leaf node that is the left child of its parent
c
+ 5678 Washington George
+ 1234 Jefferson Thomas
+ 1000 Madison James
+ 555 Lincoln Abraham
p
- 555
p
d
# Test deleting leaf node that is the right child of its parent
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
p
- 5678
p
d
# Test deleting parent node that has only a left child
c
+ 5678 Washington George
+ 1234 Jefferson Thomas
+ 1000 Madison James
+ 555 Lincoln Abraham
p
- 1000
p
d
# Test deleting parent node that has only a right child
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
p
- 1234
p
d
# Test deleting parent node that has two children
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
+ 888 Nixon Richard
p
- 1000
p
d
# Test deleting root node
c
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 555 Lincoln Abraham
p
- 1000
p
d
# Test deleting only node leaving empty tree
c
+ 888 Nixon Richard
p
- 888
p
d
# Test deleting value not in tree
c
+ 888 Nixon Richard
p
- 555
p
d
# Test deleting value from empty tree
c
- 333
p
d
# Test MakeEmpty deallocating all nodes
c
+ 1234 Jefferson Thomas
+ 888 Nixon Richard
+ 5678 Washington George
+ 555 Lincoln Abraham
+ 1000 Madison James
p
m
p
d
# Test MakeEmpty deallocating nodes from empty tree
c
p
m
p
d

View File

@ -0,0 +1,28 @@
// p05input3.txt - Test BSTree(), CopyConstructor, = , ~BSTree()
# Test Copy Constructor
c
+ 1234 Jefferson Thomas
+ 888 Nixon Richard
+ 5678 Washington George
+ 555 Lincoln Abraham
+ 1000 Madison James
p
! 007 Bond James
d
# Test Assignment Operator
c
+ 1234 Jefferson Thomas
+ 888 Nixon Richard
+ 5678 Washington George
+ 555 Lincoln Abraham
+ 1000 Madison James
p
= 007 Bond James
d

View File

@ -0,0 +1,83 @@
// p05input4.txt - Test Size()
# Test correctness of size when adding student objects
c
p
s
+ 1234 Jefferson Thomas
p
s
+ 888 Nixon Richard
p
s
+ 5678 Washington George
p
s
+ 555 Lincoln Abraham
p
s
+ 1000 Madison James
p
s
d
# Test correctness of size when deleting student objects
c
s
+ 1234 Jefferson Thomas
+ 888 Nixon Richard
+ 5678 Washington George
+ 555 Lincoln Abraham
+ 1000 Madison James
p
s
- 555
p
s
- 1234
p
s
- 888
p
s
- 5678
p
s
- 1000
p
s
d
# Test correctness of size when adding and deleting student objects
c
+ 1234 Jefferson Thomas
s
+ 888 Nixon Richard
s
+ 5678 Washington George
p
s
- 888
p
s
+ 555 Lincoln Abraham
p
s
+ 1000 Madison James
p
s
- 1234
p
s
d
# Test correctness of size for empty tree
c
p
s
d

View File

@ -0,0 +1,132 @@
// p05input5.txt - Test Min(), Max()
# Test when min is a left child
c
+ 5678 Washington George
+ 1234 Jefferson Thomas
p
<
+ 1000 Madison James
+ 555 Lincoln Abraham
p
<
d
# Test when min is root
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
p
<
d
# Test deleting parent node that has two children
c
+ 1234 Jefferson Thomas
+ 555 Lincoln Abraham
+ 1000 Madison James
p
<
+ 5678 Washington George
+ 888 Nixon Richard
p
<
d
# Test when min has a right child
c
+ 1000 Madison James
+ 1234 Jefferson Thomas
p
<
+ 555 Lincoln Abraham
+ 888 Nixon Richard
p
<
d
# Test when min is the only value
c
+ 888 Nixon Richard
p
<
d
# Test min when tree is empty
c
p
<
d
# Test when max is a left child
c
+ 5678 Washington George
+ 1234 Jefferson Thomas
+ 1000 Madison James
+ 555 Lincoln Abraham
p
>
d
# Test when max is root
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
p
>
d
# Test max when parent node that has two children
c
+ 1234 Jefferson Thomas
+ 555 Lincoln Abraham
+ 1000 Madison James
p
>
+ 5678 Washington George
+ 888 Nixon Richard
p
>
d
# Test when max has a right child
c
+ 1000 Madison James
+ 1234 Jefferson Thomas
p
>
+ 555 Lincoln Abraham
+ 888 Nixon Richard
p
>
d
# Test when max is the only value
c
+ 888 Nixon Richard
p
>
d
# Test max when tree is empty
c
p
>
d

View File

@ -0,0 +1,46 @@
// p05input6.txt - Test TotalLevels()
# Test totallevels as tree grows level by level
c
+ 555 Lincoln Abraham
p
l
+ 1000 Madison James
p
l
+ 1234 Jefferson Thomas
p
l
+ 5678 Washington George
p
l
d
# Test totallevels as with a more balance tree
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
+ 888 Nixon Richard
p
l
d
# Test totallevels with single node tree
c
+ 888 Nixon Richard
p
l
d
# Test totallevels with empty tree
c
p
l
d

View File

@ -0,0 +1,47 @@
// p05input7.txt - Test Level()
# Test level as tree grows level by level
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
p
? 555
? 1000
? 1234
? 5678
d
# Test level as with a more balance tree
c
+ 555 Lincoln Abraham
+ 1000 Madison James
+ 1234 Jefferson Thomas
+ 5678 Washington George
+ 888 Nixon Richard
p
? 555
? 1000
? 1234
? 5678
? 888
d
# Test level with single node tree
c
+ 888 Nixon Richard
p
? 888
d
# Test level with empty tree
c
p
? 888
d

BIN
CPE212/Project_05/project05 Normal file

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,66 @@
//
// student.cpp CPE 212 Fall 2010 -- Project05 - Binary Search Tree Template
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#include "student.h"
Student::Student()
// Constructor initializes sid to -1, lastname and firstname to empty string
{
sid = -1;
lastname = "";
firstname = "";
} // End Student::Student()
Student::Student(int id, string lname, string fname)
// Constructor initializes sid, lastname, firstname to id, lname, and fname respectively
{
sid = id;
lastname = lname;
firstname = fname;
} // End Student::Student()
Student::Student(const Student& s)
// Copy constructor -- copies attributes of s into attribute variables of current object
{
sid = s.sid;
lastname = s.lastname;
firstname = s.firstname;
}
bool operator==(const Student& leftop, const Student& rightop)
// Overloaded SAME AS operator
// Returns true if leftop.sid == rightop.sid. Returns false otherwise
{
return (leftop.sid == rightop.sid);
} // End operator== for Student class
bool operator<(const Student& leftop, const Student& rightop)
// Overloaded LESS THAN operator
// Returns true if leftop.sid < rightop.sid. Returns false otherwise
{
return (leftop.sid < rightop.sid);
} // End operator < for Student class
bool operator>(const Student& leftop, const Student& rightop)
// Overloaded GREATER THAN operator
// Returns true if leftop.sid > rightop.sid. Returns false otherwise
{
return (leftop.sid > rightop.sid);
} // End operator < for Student class
void Student::operator=(const Student& op) // Overloaded ASSIGNMENT operator
// Sets this->sid = op.sid, this->lastname = op.lastname, this->firstname = op.firstname
{
this->sid = op.sid;
this->lastname = op.lastname;
this->firstname = op.firstname;
} // End Student::operator=()

View File

@ -0,0 +1,83 @@
//
// student.h CPE 212 Fall 2010 -- Project05 - Binary Search Tree Template
//
// DO NOT MODIFIY OR SUBMIT THIS FILE
//
#include <iostream>
using namespace std;
#ifndef STUDENT_H
#define STUDENT_H
class Student
{
private:
int sid; // Student ID number
string lastname; // Student last name
string firstname; // Student first name
public:
/**** Start of functions to implement ****/
Student();
// Default constructor initializes sid to -1, firstname and lastname to empty string
Student(int id, string lname, string fname);
// Constructor initializes sid, lastname, firstname to id, lname, and fname respectively
Student(const Student& s);
// Copy constructor -- copies attributes of s into attribute variables of current object
friend bool operator==(const Student& leftop, const Student& rightop); // Overloaded SAME AS operator
// Returns true if leftop.sid == rightop.sid. Returns false otherwise
friend bool operator<(const Student& leftop, const Student& rightop); // Overloaded LESS THAN operator
// Returns true if leftop.sid < rightop.sid. Returns false otherwise
friend bool operator>(const Student& leftop, const Student& rightop); // Overloaded GREATER THAN operator
// Returns true if leftop.sid > rightop.sid. Returns false otherwise
void operator=(const Student& op); // Overloaded ASSIGNMENT operator
// Sets this->sid = op.sid, this->lastname = op.lastname, this->firstname = op.firstname
/***** End of functions to implement *****/
/***** Below are additional functions for your Student class -- DO NOT MOVE OR MODIFY THE CODE BELOW *****/
friend istream& operator>>(istream& leftop, Student& rightop) // Overloaded >> operator
// This allows all data associated with a Student object to be input simultaneously from an input stream
{
leftop >> rightop.sid >> rightop.lastname >> rightop.firstname;
return leftop;
}
friend ostream& operator<<(ostream& leftop, const Student& rightop) // Overloaded << operator
// This allows all data associated with a Student object to be output simultaneously to an output stream
{
leftop << "(" << rightop.sid << ", " << rightop.firstname << " " << rightop.lastname << ")";
return leftop;
}
void Print() const // Outputs student information in desired format. DO NOT MOVE OR MODIFY
{
cout << "SID: " << sid << " Name: ";
if (lastname == "")
cout << "NULL";
else
cout << lastname;
cout << ", ";
if (firstname == "")
cout << "NULL";
else
cout << firstname;
} // End Print()
};
#endif

BIN
CPE212/Project_05/student.o Normal file

Binary file not shown.

164
CPE212/Project_06/graph.cpp Normal file
View File

@ -0,0 +1,164 @@
#include "graph.h"
// Graph
Graph::Graph()
// Constructor initializes vertices linked list to empty
{
vertices = NULL;
}
//~Graph()
Graph::~Graph()
// For each VertexNode in the vertices list, Destructor deallocates all EdgeNodes before
// deallocating the VertexNode itself
{
VertexNode* delV = vertices;
EdgeNode* delE = delV->edgePtr;
while (delV != NULL)
{
while (delE != NULL)
{
delE = NULL;
delE = delE->nextPtr;
}
delV = NULL;
delV = delV->nextVertex;
}
}
// Graph::AddVertex() - adds vertex name to vertices array; assumes space is available
void Graph::AddVertex(string v)
{
VertexNode* newVert = new VertexNode; // creates memeory for newVert
newVert->vname = v; // assigns the vertex name to v
newVert->edgePtr = NULL; // sets edgePtr to NULL
newVert->nextVertex = NULL; // Sets nextVertex to NULL
}
// Graph::AddEdge() - adds edge from source to destination vertex with specified weight
// assuming source and destination are already in vertices array
void Graph::AddEdge(string s, string d, int w)
{
VertexNode* Vertex_S = WhereIs(s);
VertexNode* Vertex_D = WhereIs(d);
// Initialize newEdge
EdgeNode* newEdge = new EdgeNode;
newEdge->destination = Vertex_D;
newEdge->weight = w;
newEdge->nextPtr = NULL;
if (Vertex_S->edgePtr == NULL)
{
Vertex_S->edgePtr = newEdge;
}
else
{
// Go the the end of edgePtr and add the newEdge to it
while (Vertex_S->edgePtr->nextPtr != NULL)
{
Vertex_S->edgePtr = Vertex_S->edgePtr->nextPtr;
}
Vertex_S->edgePtr->nextPtr = newEdge;
}
}
// Graph::IsPresent() - returns true if vertex in graph, false otherwise
bool Graph::IsPresent(string v)
{
VertexNode* vertPresent = vertices;
//Traverse vertices
while (vertPresent != NULL)
{
if (vertPresent->vname == v)
return true; // found
vertPresent = vertPresent->nextVertex; // advance through graph
}
// not found
return false;
}
// WhereIs() - returns pointer to specified vertex, throws exception if vertex not present
VertexNode* Graph::WhereIs(string v)
{
VertexNode* tempVertex = vertices;
// If found
while (tempVertex != NULL)
{
if (tempVertex->vname == v)
return tempVertex; // Found
tempVertex = tempVertex->nextVertex;
}
// If not found
throw GraphVertexNotFound();
}
// Graph::WeightIs() -- returns edge weight if it exists; otherwise, throws GraphEdgeNotFound
int Graph::WeightIs(string s, string d)
{
VertexNode* sourceV = WhereIs(s);
VertexNode* destV = WhereIs(d);
// search through edge nodes
while (sourceV->edgePtr != NULL)
{
if (sourceV->edgePtr->destination == destV)
{
return sourceV->edgePtr->weight;
}
sourceV->edgePtr = sourceV->edgePtr;
}
throw GraphEdgeNotFound();
}
void Graph::MarkVertex(string v)
{
// MarkVertex()
// Marks vertex V as visited
VertexNode* vistedV = WhereIs(v);
vistedV->mark = true;
}
// Graph::IsMarked() - returns mark status of vertex; assumes vertex is present
bool Graph::IsMarked(string v)
{
VertexNode* markedV = WhereIs(v);
return markedV->mark;
}
// Graph::GetToVertices() - returns a queue q of vertices adjacent to vertex named s
void Graph::GetToVertices(string s, queue<string>& q)
{
VertexNode* tempV = WhereIs(s);
tempV = tempV->nextVertex;
while (tempV != NULL)
{
q.push(tempV->vname);
tempV = tempV->nextVertex;
}
}
// DepthFirstSearch() - Finds path through graph from start vertex to destination vertex
void Graph::DepthFirstSearch(string startVertex, string endVertex, queue<string>& path)
{
stack<string> s;
queue<string> q;
if ( !( IsPresent(startVertex) && IsPresent(endVertex) ) )
throw GraphVertexNotFound();
bool found = false;
string vertex;
string item;
// more here if required
}

154
CPE212/Project_06/graph.h Normal file
View File

@ -0,0 +1,154 @@
//
// graph.h 2010 Fall CPE 212 - Project06 - Graphs and STL
//
// Specification file for Graph class
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#ifndef GRAPH_H
#define GRAPH_H
#include <cstddef>
#include <new>
#include <iostream>
#include <iomanip>
#include <stack> // For STL stack
#include <queue> // For STL queue
#include <string>
using namespace std;
class GraphPathNotFound { }; // Exception class represents path-not-found condition
class GraphEdgeNotFound { }; // Exception class represents edge-not-found condition
class GraphVertexNotFound { }; // Exception class represents vertex-not-found condition
class GraphFull { }; // Exception class represents graph-full condition
struct VertexNode; // Forward declaration of VertexNode type
struct EdgeNode // Structure representing an edge
{
VertexNode* destination; // Pointer to destination vertex
int weight; // Edge weight
EdgeNode* nextPtr; // Pointer to next edge
};
struct VertexNode // Structure representing a vertex
{
string vname; // Name of vertex
bool mark; // Marked flag
EdgeNode* edgePtr; // Pointer to list of outgoing edges
VertexNode* nextVertex; // Pointer to next vertex in vertices list
};
class Graph // Graph ADT using adjacency list representation
{
private: //***** Private class members below *****//
VertexNode* vertices; // Linked list of vertex nodes
public: //***** Public members below *****//
Graph();
// Graph()
// Constructor initializes vertices linked list to empty
~Graph();
// ~Graph()
// For each VertexNode in the vertices list, Destructor deallocates all EdgeNodes before
// deallocating the VertexNode itself
void AddVertex(string v);
// AddVertex()
// Adds vertex to graph assuming vertex not already present
void AddEdge(string s, string d, int w);
// AddEdge()
// Adds edge from source S to destination D with specified weight W.
// If there is not enough memory to add the edge, throw the GraphFull exception
bool IsPresent(string v);
// IsPresent()
// Returns true if vertex V in graph, false otherwise
VertexNode* WhereIs(string v); /* Note: This function replaces IndexIs */
// WhereIs()
// Returns pointer to the vertex node that stores vertex v in the vertices linked list;
// Throws GraphVertexNotFound if V is not present in the vertices list
int WeightIs(string s, string d);
// WeightIs()
// Returns weight of edge (s,d). Throws GraphEdgeNotFound if edge not present.
void ClearMarks();
// ClearMarks()
// Clears all vertex marks
void MarkVertex(string v);
// MarkVertex()
// Marks vertex V as visited
bool IsMarked(string v);
// IsMarked()
// Returns true if vertex V is marked, false otherwise
void GetToVertices(string V, queue<string>& q);
// GetToVertices()
// Returns queue Q of vertex names of those vertices adjacent to vertex V
// The queue here is from the Standard Template Library
void DepthFirstSearch(string startVertex, string endVertex, queue<string>& path);
// DepthFirstSearch()
// Uses the DFS algorithm from the CPE 212 textbook to determine a path from the
// startVertex to the endVertex. If a path is found, the path vertices should
// be in the path queue. If no path is found, the path queue should be emptied
// as a signal to the client code that no path exists between the start and
// end vertices.
//
// Notes:
// (1) This algorithm is flawed in that as it searches for a path, it may
// output some additional vertices that it visited but were not part
// of the actual path. Implement the algorithm just as it appears in the textbook.
//
// (2) This algorithm requires use of the stack and queue containers from the
// Standard Template Library. The STL stack and queue interfaces may require
// minor modifications to the DFS code from the textbook.
// Print -- write graph to stdout. DO NOT MODIFY THIS FUNCTION!!!
void Print()
{
EdgeNode* eptr;
VertexNode* vptr = vertices;
const int FIELDWIDTH = 6;
string STARS = "**********";
STARS = STARS + STARS + STARS;
cout << endl << STARS << endl;
cout << setw(FIELDWIDTH) << "Vertex" << " : " << "Adjacent Vertices" << endl;
cout << "------------------------------" << endl;
while(vptr != NULL)
{
cout << setw(FIELDWIDTH) << vptr->vname << " : ";
eptr = vptr->edgePtr;
while (eptr != NULL)
{
cout << eptr->destination->vname << eptr->weight << " ";
eptr = eptr->nextPtr;
}
cout << endl;
vptr = vptr->nextVertex;
}
cout << STARS << endl << endl;
} // Graph::Print()
};
#endif

BIN
CPE212/Project_06/graph.o Normal file

Binary file not shown.

165
CPE212/Project_06/main.cpp Normal file
View File

@ -0,0 +1,165 @@
//
// main.cpp 2010 Fall CPE 212 - Project06 - Graphs and STL
//
// Driver program for Graph class -- The text files (read by this code) contain a series
// of commands that will help you test your Graph ADT code by triggering various class methods.
//
// DO NOT MODIFY OR SUBMIT THIS FILE
//
#include <iostream>
#include <fstream>
#include "graph.h"
#include <stack> // For STL stack class
#include <queue> // For STL queue class
using namespace std;
int main(int argc, char* argv[])
{
ifstream inputs; // Input file for commands
char op, ch; // Hold operation and optional char input
Graph* gPtr = NULL; // Will point to Graph object
int num; // Holds number of graph nodes
string v1, v2; // Vertex names input from file
int w; // Edge weight input from file
queue<string> path; // Computed path
string comment; // Comment input from file
// Output usage message if one input file name is not provided
if (argc != 2)
{
cout << "Usage:\n project07 <inputfile>\n";
return 1;
}
// Attempt to open input file -- terminate if file does not open
inputs.open(argv[1]);
if (!inputs)
{
cout << "Error - unable to open input file" << endl;
return 1;
}
cout << endl;
// Process commands from input file
getline(inputs, comment);
cout << comment << endl;
inputs >> op; // Attempt to input number of vertices
while (inputs)
{
switch (op)
{
case '#': // Comment
getline(inputs, comment);
cout << comment << endl;
break;
case 'c': // Add vertex
cout << "Constructor()" << endl;
gPtr = new Graph();
break;
case 'v': // Add vertex
inputs >> v1;
cout << "AddVertex(" << v1 << ")" << endl;
gPtr->AddVertex(v1);
break;
case 'd': // Add directed edge
inputs >> v1 >> v2 >> w;
cout << "AddEdge(" << v1 << ", " << v2 << ", " << w << ")" << endl;
gPtr->AddEdge(v1, v2, w);
break;
case 'u': // Add undirected edge
inputs >> v1 >> v2 >> w;
cout << "AddEdge(" << v1 << ", " << v2 << ", " << w << ")" << endl;
gPtr->AddEdge(v1, v2, w);
cout << "AddEdge(" << v2 << ", " << v1 << ", " << w << ")" << endl;
gPtr->AddEdge(v2, v1, w);
break;
case '?': // IsPresent()
inputs >> v1;
if (gPtr->IsPresent(v1))
cout << "IsPresent(" << v1 << ") -- true" << endl;
else
cout << "IsPresent(" << v1 << ") -- false" << endl;
break;
case 'w': // WeightIs()
inputs >> v1 >> v2;
try
{
cout << "WeightIs(" << v1 << ", " << v2 << ") -- ";
w = gPtr->WeightIs(v1, v2);
cout << w << endl;
}
catch ( GraphVertexNotFound )
{
cout << "Error: vertex not found" << endl;
}
catch ( GraphEdgeNotFound )
{
cout << "Error: edge not found" << endl;
}
break;
case 's': // Perform Depth-First Search
inputs >> v1 >> v2; // Input v1-start and v2-end vertices
cout << "DFS( " << v1 << ", " << v2 << " ) -- ";
try
{
gPtr->DepthFirstSearch(v1, v2, path);
if (path.empty())
cout << "No path found" << endl;
else
{
cout << " { ";
while (!path.empty())
{
cout << path.front() << " ";
path.pop();
}
cout << "}" << endl;
}
}
catch ( GraphVertexNotFound )
{
cout << "Error: vertex not found" << endl;
}
while (!path.empty())
path.pop();
break;
case 'p': // Print Graph
gPtr->Print();
break;
case '~': // Destructor
delete gPtr;
gPtr = NULL;
cout << "Destructor()" << endl << endl;
break;
default: // Error
cout << "Error - unrecognized operation '" << op << "'" << endl;
cout << "Terminating now..." << endl;
return 1;
break;
}
inputs >> op; // Attempt to input next command
}
return 0;
}

BIN
CPE212/Project_06/main.o Normal file

Binary file not shown.

View File

@ -0,0 +1,15 @@
# Project06 makefile
project06: graph.o main.o
g++ graph.o main.o -o project06
graph.o: graph.h graph.cpp
g++ -c graph.cpp
main.o: graph.h main.cpp
g++ -c main.cpp
clean:
rm *.o project06

View File

@ -0,0 +1,41 @@
# p06input1.txt - Test Graph(), ~Graph(), AddVertex(), AddEdge() with undirected graph
c
v A
v B
v C
v D
u A B 5
u A C 10
u B C 15
u B D 25
u C D 20
p
~
c
v A
v B
v C
v D
v E
v F
v G
v H
u A B 25
u A C 10
u A E 60
u B G 75
u B H 15
u C E 15
u D F 25
u D H 80
u E G 35
u E F 5
u F H 40
p
~

View File

@ -0,0 +1,40 @@
# p06input2.txt - Test Graph(), ~Graph(), AddVertex(), AddEdge() with directed graph
c
v A
v B
v C
v D
d A B 5
d A C 10
d B C 15
d B D 25
d C D 20
p
~
c
v A
v B
v C
v D
v E
v F
v G
v H
d A B 25
d A C 10
d A E 60
d B G 75
d B H 15
d C E 15
d D F 25
d D H 80
d E G 35
d E F 5
d F H 40
p
~

Some files were not shown because too many files have changed in this diff Show More