SlideShare a Scribd company logo
1 of 10
Download to read offline
Complete DB code following the instructions:
Implement the DB and use the unittest_db() function to test it. DO NOT CHANGE THIS CODE
FOR YOUR SUBMISSION, as it will be used to test your code against the answers (with different
input files).
a) The student ID should be the base class's key member.
b) The student ID should be automatically assigned such that the ID/key should be n if the student
is the nth student to join the school. If the student later leaves (i.e., deleted from the BST), the ID
does NOT get reassigned to another student. Thus, the student ID of the last student to join the
school should reflect the TOTAL number of students that have joined this school since its
reception (regardless of whether some have left).
5. Test your code against the provided input and output files.
a) The provided answer for the BST unit test is in "unittest_ans_t100_s100.txt". The s100 refers to
the seed of 100 (-s 100), and t100 refers to the number of elements to add to the BST (-t 100).
b) The provided answer for the DB is in "students_1_ans.txt" for the "students_1.txt" input file.
6. Make sure your code has no memory leaks (using valgrind).
7. Your code should work beyond the provided unit tests. That is, even if it does work for all the
given tests, if the code has an identifiable bug (i.e., by reading the source code), points WILL be
deducted.
For example, if I were to change
unittest_bst(num_test, seed, cout, 5); ->
unittest_bst(num_test, seed, cout, 100);
it should still work.
db.h
#ifndef DB_H_
#define DB_H_
#include <iostream>
#include "bst.h"
using namespace std;
class SNode : public Node {
private:
string first;
string last;
unsigned int age;
static unsigned int num_students;
public:
// Constructors and destructor
SNode();
SNode(string f_, string l_, unsigned int a_);
~SNode();
// public interface
void change_first(string f_);
void change_last(string l_);
string get_first();
string get_last();
unsigned int get_age();
void print_info(ostream& to);
};
#endif
main.cc
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <getopt.h>
#include "bst.h"
#include "db.h"
using namespace std;
const char* const short_opt = ":ht:s:i:o:";
const struct option long_opt[] = {
{"help", 0, NULL, 'h'},
{"test", 1, NULL, 't'},
{"seed", 1, NULL, 's'},
{"input", 1, NULL, 'i'},
{"output", 1, NULL, 'o'},
{NULL, 0, NULL, 0}
};
void usage(char* argv);
void unittest_bst(unsigned int n, unsigned int seed, ostream& to,
unsigned int remain);
bool read_db(const string file_name, vector<string>& firsts,
vector<string>& lasts, vector<unsigned int>& ages);
void create_db(BST& db, const vector<string> f_, const vector<string> l_,
const vector<unsigned int> a_);
bool unittest_db(string ifile_name, string ofile_name);
/* Main function
*/
int main(int argc, char **argv)
{
int c = 0;
string test = "0";
string seed_str = "0";
string ifile_name;
string ofile_name;
if(argc < 2) {
usage(argv[0]);
return 0;
}
while((c = getopt_long(argc, argv, short_opt, long_opt, NULL)) != -1) {
switch(c) {
case 'h':
usage(argv[0]);
return 0;
case 't':
test = optarg;
break;
case 's':
seed_str = optarg;
break;
case 'i':
ifile_name = optarg;
break;
case 'o':
ofile_name = optarg;
break;
default:
usage(argv[0]);
exit(EXIT_FAILURE);
}
}
// Unit Test
int num_test = stoi(test);
if(num_test > 0) {
int seed = stoi(seed_str);
unittest_bst(num_test, seed, cout, 5);
}
// Check if input and output files were specified
if(ifile_name.empty() || ofile_name.empty()) {
usage(argv[0]);
return -1;
}
if(!unittest_db(ifile_name, ofile_name)) {
return -1;
}
return 0;
}
/* Print information on how to properly use this program
*/
void usage(char* call)
{
cout << "Usage: " << call << endl;
cout << "Options:" << endl;
cout << "t-h or --help Display this information" << endl;
cout << "t-t or --test n BST Unit Test with n elements" << endl;
cout << "t-s or --seed s Rand # seed value" << endl;
cout << "t-i or --input ifname Input file" << endl;
cout << "t-o or --output ofname Output file" << endl;
}
void unittest_bst(unsigned int n, unsigned int seed, ostream& to,
unsigned int remain)
{
to << "Unit Test for baseline BST implementation" << endl;
srand(seed);
vector<int> keys(n);
for(unsigned int i = 0; i < keys.size(); i++) {
keys[i] = rand() % 100;
}
int num_keys = keys.size();
/* or you can specify keys manually */
/* Make sure this is commented out for the final submission */
#if 0
keys[0] = 15;
keys[1] = 10;
keys[2] = 20;
keys[3] = 8;
keys[4] = 12;
keys[5] = 16;
keys[6] = 25;
num_keys = 7;
keys.resize(num_keys);
keys.shrink_to_fit();
#endif
#if 0
keys[0] = 100;
keys[1] = 1;
keys[2] = 150;
keys[3] = 101;
keys[4] = 23;
keys[5] = 47;
num_keys = 6;
keys.resize(num_keys);
keys.shrink_to_fit();
#endif
// Unsorted numbers
to << "Input: " << endl;
for(int i = 0; i < num_keys; i++) {
to << keys[i] << " ";
}
to << endl;
// Sorted numbers should look like...
vector<int> tmp = keys;
sort(tmp.begin(), tmp.end());
to << "Sorted input: " << endl;
for(int i = 0; i < num_keys; i++) {
to << tmp[i] << " ";
}
to << endl;
// insert_node() test
Node** nodes = new Node*[num_keys];
BST my_BST;
for(int i = 0; i < num_keys; i++) {
nodes[i] = new Node(keys[i]);
my_BST.insert_node(nodes[i]);
}
// tree_min() and tree_max() test
to << "----------" << endl;
to << "BST min: " << my_BST.tree_min()->get_key() << endl;
to << "BST max: " << my_BST.tree_max()->get_key() << endl;
to << "----------" << endl;
// walk() test
to << "----------" << endl;
to << "BST walk" << endl;
my_BST.walk(to);
to << "----------" << endl;
// get_pred() and get_succ() test
to << "----------" << endl;
to << "Predecessor/Successor" << endl;
for(int i = 0; i < num_keys; i++) {
to << nodes[i]->get_key();
if(my_BST.get_pred(nodes[i]) != nullptr) {
to << " pred: " << my_BST.get_pred(nodes[i])->get_key();
} else {
to << " pred: " << "none";
}
if(my_BST.get_succ(nodes[i]) != nullptr) {
to << " succ: " << my_BST.get_succ(nodes[i])->get_key() << endl;
} else {
to << " succ: " << "none" << endl;;
}
}
to << "----------" << endl;
// tree_search() test
to << "----------" << endl;
to << "tree_search() with fake keys" << endl;
for(int i = 0; i < num_keys; i++) {
Node* tmp = my_BST.tree_search(keys[i] + 1);
if(tmp != nullptr) {
to << "Found " << tmp->get_key() << endl;
} else {
to << keys[i] + 1 << " was not found" << endl;
}
}
to << "----------" << endl;
// tree_search() and delete_node() test
to << "----------" << endl;
to << "tree_search() and delete_node()" << endl;
for(unsigned int i = 0; i < num_keys - remain; i++) {
to << "---- deleting " << keys[i] << "-----" << endl;
Node* tmp = my_BST.tree_search(keys[i]);
if(tmp != nullptr) {
my_BST.delete_node(tmp);
my_BST.walk(to);
} else {
to << keys[i] << " was not found" << endl;
}
}
to << "----------" << endl;
// Cleanup
delete [] nodes;
}
bool read_db(const string file_name, vector<string>& firsts,
vector<string>& lasts, vector<unsigned int>& ages)
{
bool ret = true;
ifstream inFile(file_name);
string line;
while(getline(inFile, line)) {
stringstream sline(line);
string token;
getline(sline, token, ' ');
firsts.push_back(token);
getline(sline, token, ' ');
lasts.push_back(token);
getline(sline, token, ' ');
int age_;
stringstream(token) >> age_;
ages.push_back(age_);
}
if(!((firsts.size() == lasts.size()) && (firsts.size() == ages.size()))) {
cerr << "List sizes are not equal" << endl;
ret = false;
}
inFile.close();
return ret;
}
void create_db(BST& db, const vector<string> f_, const vector<string> l_,
const vector<unsigned int> a_)
{
for(unsigned int i = 0; i < f_.size(); i++) {
SNode* st = new SNode(f_[i], l_[i], a_[i]);
db.insert_node(st);
}
}
bool unittest_db(string ifile_name, string ofile_name)
{
vector<string> first_names;
vector<string> last_names;
vector<unsigned int> ages;
if(!read_db(ifile_name, first_names, last_names, ages)) {
return false;
}
BST student_db;
create_db(student_db, first_names, last_names, ages);
ofstream outFile(ofile_name);
outFile << "-------------------------------------------------" << endl;
student_db.walk(outFile);
outFile << "-------------------------------------------------" << endl;
outFile << "First student ever: " << endl;
student_db.tree_min()->print_info(outFile);
outFile << "Last student to join: " << endl;
student_db.tree_max()->print_info(outFile);
unsigned int n = 36;
outFile << "Information on student: " << n << endl;
student_db.tree_search(n)->print_info(outFile);
outFile << "Removing student...";
student_db.delete_node(student_db.tree_search(n));
SNode* tmp = (SNode*) student_db.tree_search(n);
if(tmp == nullptr) {
outFile << "student successfully removed" << endl;
} else {
outFile << "error removing student" << endl;
}
outFile << "-------------------------------------------------" << endl;
student_db.walk(outFile);
outFile << "-------------------------------------------------" << endl;
outFile.close();
return true;
}
COMPLETE db.cc
#include "db.h"
// ---------------------------------------------
// SNode class
// Default constructor
// TODO: Implement this
// BASIC function header is provided for so that the code will compile
// The actual function header may be different
SNode::SNode()
{
}
// Constructor
// TODO: Implement this
// BASIC function header is provided for so that the code will compile
// The actual function header may be different
SNode::SNode(string f_, string l_, unsigned int a_)
{
}
// Destructor
SNode::~SNode()
{
// TODO: Implement this
}
unsigned int SNode::num_students = 0;
// Public interface
void SNode::change_first(string f_)
{
// TODO: Implement this
}
void SNode::change_last(string l_)
{
// TODO: Implement this
}
string SNode::get_first()
{
// TODO: Implement this
}
string SNode::get_last()
{
// TODO: Implement this
}
unsigned int SNode::get_age()
{
// TODO: Implement this
}
// Print information about the student
// do not change this
void SNode::print_info(ostream& to)
{
to << "Student ID: " << this->get_key()
<< "tFirst: " << this->first
<< "tLast: " << this->last
<< "tAge: " << this->age << endl;
}
// ---------------------------------------------

More Related Content

Similar to Complete DB code following the instructions Implement the D.pdf

C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdfC++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
aassecuritysystem
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
kostikjaylonshaewe47
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdf
arjuncollection
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
shreeaadithyaacellso
 
ch5_additional.ppt
ch5_additional.pptch5_additional.ppt
ch5_additional.ppt
LokeshK66
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
HIMANSUKUMAR12
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
GkhanGirgin3
 

Similar to Complete DB code following the instructions Implement the D.pdf (20)

C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdfC++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
C++ Language -- Dynamic Memory -- There are 7 files in this project- a.pdf
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
 
Language is C++ I'm having trouble making my code meet these requireme.docx
Language is C++ I'm having trouble making my code meet these requireme.docxLanguage is C++ I'm having trouble making my code meet these requireme.docx
Language is C++ I'm having trouble making my code meet these requireme.docx
 
C++ L07-Struct
C++ L07-StructC++ L07-Struct
C++ L07-Struct
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
So I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdfSo I already have most of the code and now I have to1. create an .pdf
So I already have most of the code and now I have to1. create an .pdf
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
 
oodp elab.pdf
oodp elab.pdfoodp elab.pdf
oodp elab.pdf
 
I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Codes on structures
Codes on structuresCodes on structures
Codes on structures
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit Testing
 
Lab 13
Lab 13Lab 13
Lab 13
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
 
ch5_additional.ppt
ch5_additional.pptch5_additional.ppt
ch5_additional.ppt
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
booksoncprogramminglanguage-anintroductiontobeginnersbyarunumrao4-21101016591...
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 

More from access2future1

The Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdf
The Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdfThe Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdf
The Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdf
access2future1
 
Second Republic Bank is a lending company that operates in t.pdf
Second Republic Bank is a lending company that operates in t.pdfSecond Republic Bank is a lending company that operates in t.pdf
Second Republic Bank is a lending company that operates in t.pdf
access2future1
 
Proporcione ejemplos de cmo Chris y Alison participaron en .pdf
Proporcione ejemplos de cmo Chris y Alison participaron en .pdfProporcione ejemplos de cmo Chris y Alison participaron en .pdf
Proporcione ejemplos de cmo Chris y Alison participaron en .pdf
access2future1
 
PLEASE HELP ME Eric Christopher Associate Director for Glo.pdf
PLEASE HELP ME Eric Christopher Associate Director for Glo.pdfPLEASE HELP ME Eric Christopher Associate Director for Glo.pdf
PLEASE HELP ME Eric Christopher Associate Director for Glo.pdf
access2future1
 
Patient Documentation Analysis Due Date Sunday 1159 pm MT.pdf
Patient Documentation Analysis Due Date Sunday 1159 pm MT.pdfPatient Documentation Analysis Due Date Sunday 1159 pm MT.pdf
Patient Documentation Analysis Due Date Sunday 1159 pm MT.pdf
access2future1
 
Please fix the following C++ code to compile correctly in Vi.pdf
Please fix the following C++ code to compile correctly in Vi.pdfPlease fix the following C++ code to compile correctly in Vi.pdf
Please fix the following C++ code to compile correctly in Vi.pdf
access2future1
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdf
access2future1
 
i am trying to add the first four lines of a studenttxt int.pdf
i am trying to add the first four lines of a studenttxt int.pdfi am trying to add the first four lines of a studenttxt int.pdf
i am trying to add the first four lines of a studenttxt int.pdf
access2future1
 

More from access2future1 (20)

The following stockholders equity accounts arranged alphabe.pdf
The following stockholders equity accounts arranged alphabe.pdfThe following stockholders equity accounts arranged alphabe.pdf
The following stockholders equity accounts arranged alphabe.pdf
 
You are considering a stock investment in one of two firms .pdf
You are considering a stock investment in one of two firms .pdfYou are considering a stock investment in one of two firms .pdf
You are considering a stock investment in one of two firms .pdf
 
The Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdf
The Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdfThe Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdf
The Case of Sam Sawyer Sam Sawyer was a toprated operator i.pdf
 
Second Republic Bank is a lending company that operates in t.pdf
Second Republic Bank is a lending company that operates in t.pdfSecond Republic Bank is a lending company that operates in t.pdf
Second Republic Bank is a lending company that operates in t.pdf
 
Researchers found that a person in a particular country spen.pdf
Researchers found that a person in a particular country spen.pdfResearchers found that a person in a particular country spen.pdf
Researchers found that a person in a particular country spen.pdf
 
QUESTION 2 internal rate of return method 14 RETURN USE N.pdf
QUESTION 2 internal rate of return method 14 RETURN  USE N.pdfQUESTION 2 internal rate of return method 14 RETURN  USE N.pdf
QUESTION 2 internal rate of return method 14 RETURN USE N.pdf
 
Question 17 Which of the following contributes directly to t.pdf
Question 17 Which of the following contributes directly to t.pdfQuestion 17 Which of the following contributes directly to t.pdf
Question 17 Which of the following contributes directly to t.pdf
 
Proporcione ejemplos de cmo Chris y Alison participaron en .pdf
Proporcione ejemplos de cmo Chris y Alison participaron en .pdfProporcione ejemplos de cmo Chris y Alison participaron en .pdf
Proporcione ejemplos de cmo Chris y Alison participaron en .pdf
 
Please Use SWISH and write the code answer each part carefu.pdf
Please Use SWISH and write the code answer each part carefu.pdfPlease Use SWISH and write the code answer each part carefu.pdf
Please Use SWISH and write the code answer each part carefu.pdf
 
PLEASE HELP ME Eric Christopher Associate Director for Glo.pdf
PLEASE HELP ME Eric Christopher Associate Director for Glo.pdfPLEASE HELP ME Eric Christopher Associate Director for Glo.pdf
PLEASE HELP ME Eric Christopher Associate Director for Glo.pdf
 
please help with the fill in the blanks Fill in the followin.pdf
please help with the fill in the blanks Fill in the followin.pdfplease help with the fill in the blanks Fill in the followin.pdf
please help with the fill in the blanks Fill in the followin.pdf
 
Patient Documentation Analysis Due Date Sunday 1159 pm MT.pdf
Patient Documentation Analysis Due Date Sunday 1159 pm MT.pdfPatient Documentation Analysis Due Date Sunday 1159 pm MT.pdf
Patient Documentation Analysis Due Date Sunday 1159 pm MT.pdf
 
Please fix the following C++ code to compile correctly in Vi.pdf
Please fix the following C++ code to compile correctly in Vi.pdfPlease fix the following C++ code to compile correctly in Vi.pdf
Please fix the following C++ code to compile correctly in Vi.pdf
 
output and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdfoutput and explain There is Mylist There is MyArrayList pa.pdf
output and explain There is Mylist There is MyArrayList pa.pdf
 
Name the hormones that influence the menstrual cycle Ident.pdf
Name the hormones that influence the menstrual cycle  Ident.pdfName the hormones that influence the menstrual cycle  Ident.pdf
Name the hormones that influence the menstrual cycle Ident.pdf
 
Mike and Carol Brady realized that their house was not big e.pdf
Mike and Carol Brady realized that their house was not big e.pdfMike and Carol Brady realized that their house was not big e.pdf
Mike and Carol Brady realized that their house was not big e.pdf
 
Debugging C Console Program Debug the program to identify .pdf
Debugging C Console Program Debug the program to identify .pdfDebugging C Console Program Debug the program to identify .pdf
Debugging C Console Program Debug the program to identify .pdf
 
742 Example 743 Continued Suppose that we have iid Ber.pdf
742 Example 743 Continued Suppose that we have iid Ber.pdf742 Example 743 Continued Suppose that we have iid Ber.pdf
742 Example 743 Continued Suppose that we have iid Ber.pdf
 
Holt Enterprises recently paid a dividend D0 of 275 It .pdf
Holt Enterprises recently paid a dividend D0 of 275 It .pdfHolt Enterprises recently paid a dividend D0 of 275 It .pdf
Holt Enterprises recently paid a dividend D0 of 275 It .pdf
 
i am trying to add the first four lines of a studenttxt int.pdf
i am trying to add the first four lines of a studenttxt int.pdfi am trying to add the first four lines of a studenttxt int.pdf
i am trying to add the first four lines of a studenttxt int.pdf
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

Complete DB code following the instructions Implement the D.pdf

  • 1. Complete DB code following the instructions: Implement the DB and use the unittest_db() function to test it. DO NOT CHANGE THIS CODE FOR YOUR SUBMISSION, as it will be used to test your code against the answers (with different input files). a) The student ID should be the base class's key member. b) The student ID should be automatically assigned such that the ID/key should be n if the student is the nth student to join the school. If the student later leaves (i.e., deleted from the BST), the ID does NOT get reassigned to another student. Thus, the student ID of the last student to join the school should reflect the TOTAL number of students that have joined this school since its reception (regardless of whether some have left). 5. Test your code against the provided input and output files. a) The provided answer for the BST unit test is in "unittest_ans_t100_s100.txt". The s100 refers to the seed of 100 (-s 100), and t100 refers to the number of elements to add to the BST (-t 100). b) The provided answer for the DB is in "students_1_ans.txt" for the "students_1.txt" input file. 6. Make sure your code has no memory leaks (using valgrind). 7. Your code should work beyond the provided unit tests. That is, even if it does work for all the given tests, if the code has an identifiable bug (i.e., by reading the source code), points WILL be deducted. For example, if I were to change unittest_bst(num_test, seed, cout, 5); -> unittest_bst(num_test, seed, cout, 100); it should still work. db.h #ifndef DB_H_ #define DB_H_ #include <iostream> #include "bst.h" using namespace std; class SNode : public Node { private: string first; string last; unsigned int age; static unsigned int num_students; public: // Constructors and destructor SNode(); SNode(string f_, string l_, unsigned int a_); ~SNode(); // public interface void change_first(string f_);
  • 2. void change_last(string l_); string get_first(); string get_last(); unsigned int get_age(); void print_info(ostream& to); }; #endif main.cc #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <algorithm> #include <getopt.h> #include "bst.h" #include "db.h" using namespace std; const char* const short_opt = ":ht:s:i:o:"; const struct option long_opt[] = { {"help", 0, NULL, 'h'}, {"test", 1, NULL, 't'}, {"seed", 1, NULL, 's'}, {"input", 1, NULL, 'i'}, {"output", 1, NULL, 'o'}, {NULL, 0, NULL, 0} }; void usage(char* argv); void unittest_bst(unsigned int n, unsigned int seed, ostream& to, unsigned int remain); bool read_db(const string file_name, vector<string>& firsts, vector<string>& lasts, vector<unsigned int>& ages); void create_db(BST& db, const vector<string> f_, const vector<string> l_, const vector<unsigned int> a_); bool unittest_db(string ifile_name, string ofile_name); /* Main function */ int main(int argc, char **argv) { int c = 0; string test = "0";
  • 3. string seed_str = "0"; string ifile_name; string ofile_name; if(argc < 2) { usage(argv[0]); return 0; } while((c = getopt_long(argc, argv, short_opt, long_opt, NULL)) != -1) { switch(c) { case 'h': usage(argv[0]); return 0; case 't': test = optarg; break; case 's': seed_str = optarg; break; case 'i': ifile_name = optarg; break; case 'o': ofile_name = optarg; break; default: usage(argv[0]); exit(EXIT_FAILURE); } } // Unit Test int num_test = stoi(test); if(num_test > 0) { int seed = stoi(seed_str); unittest_bst(num_test, seed, cout, 5); } // Check if input and output files were specified if(ifile_name.empty() || ofile_name.empty()) { usage(argv[0]); return -1; } if(!unittest_db(ifile_name, ofile_name)) { return -1;
  • 4. } return 0; } /* Print information on how to properly use this program */ void usage(char* call) { cout << "Usage: " << call << endl; cout << "Options:" << endl; cout << "t-h or --help Display this information" << endl; cout << "t-t or --test n BST Unit Test with n elements" << endl; cout << "t-s or --seed s Rand # seed value" << endl; cout << "t-i or --input ifname Input file" << endl; cout << "t-o or --output ofname Output file" << endl; } void unittest_bst(unsigned int n, unsigned int seed, ostream& to, unsigned int remain) { to << "Unit Test for baseline BST implementation" << endl; srand(seed); vector<int> keys(n); for(unsigned int i = 0; i < keys.size(); i++) { keys[i] = rand() % 100; } int num_keys = keys.size(); /* or you can specify keys manually */ /* Make sure this is commented out for the final submission */ #if 0 keys[0] = 15; keys[1] = 10; keys[2] = 20; keys[3] = 8; keys[4] = 12; keys[5] = 16; keys[6] = 25; num_keys = 7; keys.resize(num_keys); keys.shrink_to_fit(); #endif #if 0 keys[0] = 100;
  • 5. keys[1] = 1; keys[2] = 150; keys[3] = 101; keys[4] = 23; keys[5] = 47; num_keys = 6; keys.resize(num_keys); keys.shrink_to_fit(); #endif // Unsorted numbers to << "Input: " << endl; for(int i = 0; i < num_keys; i++) { to << keys[i] << " "; } to << endl; // Sorted numbers should look like... vector<int> tmp = keys; sort(tmp.begin(), tmp.end()); to << "Sorted input: " << endl; for(int i = 0; i < num_keys; i++) { to << tmp[i] << " "; } to << endl; // insert_node() test Node** nodes = new Node*[num_keys]; BST my_BST; for(int i = 0; i < num_keys; i++) { nodes[i] = new Node(keys[i]); my_BST.insert_node(nodes[i]); } // tree_min() and tree_max() test to << "----------" << endl; to << "BST min: " << my_BST.tree_min()->get_key() << endl; to << "BST max: " << my_BST.tree_max()->get_key() << endl; to << "----------" << endl; // walk() test to << "----------" << endl; to << "BST walk" << endl; my_BST.walk(to); to << "----------" << endl; // get_pred() and get_succ() test
  • 6. to << "----------" << endl; to << "Predecessor/Successor" << endl; for(int i = 0; i < num_keys; i++) { to << nodes[i]->get_key(); if(my_BST.get_pred(nodes[i]) != nullptr) { to << " pred: " << my_BST.get_pred(nodes[i])->get_key(); } else { to << " pred: " << "none"; } if(my_BST.get_succ(nodes[i]) != nullptr) { to << " succ: " << my_BST.get_succ(nodes[i])->get_key() << endl; } else { to << " succ: " << "none" << endl;; } } to << "----------" << endl; // tree_search() test to << "----------" << endl; to << "tree_search() with fake keys" << endl; for(int i = 0; i < num_keys; i++) { Node* tmp = my_BST.tree_search(keys[i] + 1); if(tmp != nullptr) { to << "Found " << tmp->get_key() << endl; } else { to << keys[i] + 1 << " was not found" << endl; } } to << "----------" << endl; // tree_search() and delete_node() test to << "----------" << endl; to << "tree_search() and delete_node()" << endl; for(unsigned int i = 0; i < num_keys - remain; i++) { to << "---- deleting " << keys[i] << "-----" << endl; Node* tmp = my_BST.tree_search(keys[i]); if(tmp != nullptr) { my_BST.delete_node(tmp); my_BST.walk(to); } else { to << keys[i] << " was not found" << endl; } }
  • 7. to << "----------" << endl; // Cleanup delete [] nodes; } bool read_db(const string file_name, vector<string>& firsts, vector<string>& lasts, vector<unsigned int>& ages) { bool ret = true; ifstream inFile(file_name); string line; while(getline(inFile, line)) { stringstream sline(line); string token; getline(sline, token, ' '); firsts.push_back(token); getline(sline, token, ' '); lasts.push_back(token); getline(sline, token, ' '); int age_; stringstream(token) >> age_; ages.push_back(age_); } if(!((firsts.size() == lasts.size()) && (firsts.size() == ages.size()))) { cerr << "List sizes are not equal" << endl; ret = false; } inFile.close(); return ret; } void create_db(BST& db, const vector<string> f_, const vector<string> l_, const vector<unsigned int> a_) { for(unsigned int i = 0; i < f_.size(); i++) { SNode* st = new SNode(f_[i], l_[i], a_[i]); db.insert_node(st); } } bool unittest_db(string ifile_name, string ofile_name) { vector<string> first_names; vector<string> last_names;
  • 8. vector<unsigned int> ages; if(!read_db(ifile_name, first_names, last_names, ages)) { return false; } BST student_db; create_db(student_db, first_names, last_names, ages); ofstream outFile(ofile_name); outFile << "-------------------------------------------------" << endl; student_db.walk(outFile); outFile << "-------------------------------------------------" << endl; outFile << "First student ever: " << endl; student_db.tree_min()->print_info(outFile); outFile << "Last student to join: " << endl; student_db.tree_max()->print_info(outFile); unsigned int n = 36; outFile << "Information on student: " << n << endl; student_db.tree_search(n)->print_info(outFile); outFile << "Removing student..."; student_db.delete_node(student_db.tree_search(n)); SNode* tmp = (SNode*) student_db.tree_search(n); if(tmp == nullptr) { outFile << "student successfully removed" << endl; } else { outFile << "error removing student" << endl; } outFile << "-------------------------------------------------" << endl; student_db.walk(outFile); outFile << "-------------------------------------------------" << endl; outFile.close(); return true; } COMPLETE db.cc #include "db.h" // --------------------------------------------- // SNode class // Default constructor // TODO: Implement this // BASIC function header is provided for so that the code will compile // The actual function header may be different SNode::SNode() { }
  • 9. // Constructor // TODO: Implement this // BASIC function header is provided for so that the code will compile // The actual function header may be different SNode::SNode(string f_, string l_, unsigned int a_) { } // Destructor SNode::~SNode() { // TODO: Implement this } unsigned int SNode::num_students = 0; // Public interface void SNode::change_first(string f_) { // TODO: Implement this } void SNode::change_last(string l_) { // TODO: Implement this } string SNode::get_first() { // TODO: Implement this } string SNode::get_last() { // TODO: Implement this } unsigned int SNode::get_age() { // TODO: Implement this } // Print information about the student // do not change this void SNode::print_info(ostream& to) { to << "Student ID: " << this->get_key() << "tFirst: " << this->first << "tLast: " << this->last << "tAge: " << this->age << endl;