adding cs142 code

This commit is contained in:
Derek McQuay 2016-04-06 20:45:34 -07:00
parent 552d456d53
commit 8e52ce1982
174 changed files with 14064 additions and 0 deletions

31
cs142/final/Makefile Normal file
View File

@ -0,0 +1,31 @@
CXXFLAGS= -Wall -g
OBJECTS=main.o employee.o hourly.o salaried.o administrator.o faculty.o util.o campus.o
EXE=main
all: $(EXE)
$(EXE): main.o
$(CXX) $(CXXFLAGS) $(OBJECTS) -o $@
main.o: main.cpp employee.o hourly.o salaried.o administrator.o faculty.o util.o campus.o
employee.o: employee.h employee.cpp
hourly.o: hourly.cpp hourly.h employee.h
salaried.o: salaried.h salaried.cpp employee.h
administrator.o: administrator.cpp administrator.h employee.h
faculty.o: faculty.cpp faculty.h employee.h
util.o: util.h util.cpp
campus.o: campus.cpp campus.h
run: $(EXE)
@./$(EXE)
clean:
@rm -vf *.o
@rm -vf $(EXE)
debug: $(EXE)
gdb ./$(EXE)
valgrind: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE)

View File

@ -0,0 +1,14 @@
#include "administrator.h"
#include "employee.h"
using namespace std;
administrator::administrator(string name, double pay_rate, int hours, string type) :
employee(name, pay_rate, hours, type) {}
int administrator::get_salary() {
if(hours > 170) {
pay_rate += pay_rate * .1;
}
return pay_rate;
}

View File

@ -0,0 +1,15 @@
#ifndef __ADMINISTRATOR_H__
#define __ADMINISTRATOR_H__
#include <iostream>
#include "employee.h"
using namespace std;
class administrator : public employee {
public:
administrator(string name, double pay_rate, int hours, string type);
int get_salary();
};
#endif

263
cs142/final/campus.cpp Normal file
View File

@ -0,0 +1,263 @@
#include "campus.h"
#include "salaried.h"
#include "hourly.h"
#include "faculty.h"
#include "administrator.h"
#include "util.h"
#include <iostream>
#include <vector>
#include <cstdlib>
#include <fstream>
bool campus::contains(string name) { //function used to verify if the string is already included
employee * f = NULL;
for(unsigned int i = 0; i < workers.size(); i++) {
f = dynamic_cast<employee *>(workers[i]);
if(f->get_name() == name) {
return true;
}
}
return false;
}
void campus::add_worker_from_parse(string name, string type, double pay_rate) { //add worker for parsed input
bool passed = false;
employee * h = NULL;
int hours = 0;
if(type == "H") {
h = new hourly(name, pay_rate, hours, type);
passed = true;
}
else if(type == "S") {
h = new salaried(name, pay_rate, hours, type);
passed = true;
}
else if(type == "F") {
h = new faculty(name, pay_rate, hours, type);
passed = true;
}
else if(type == "A") {
h = new administrator(name, pay_rate, hours, type);
passed = true;
}
if(passed == true) {
workers.push_back(h);
}
}
void campus::add_worker() { //general add worker function which it gets the input
employee * h = NULL;
bool passed;
string info;
string name, type;
int hours = 0;
double pay_rate = 0;
cout << "Enter info in following format" << endl;
cout << "type pay_rate name" << endl;;
getline(cin, info);
passed = parse_n_load(info, name, type, pay_rate);
if(contains(name) == true) {
cout << "already exists" << endl;
return;
}
if(passed == false) {
cout << "incorrect entry" << endl;
}
if(info[0] == ' ') {
cout << "incorrect entry" << endl;
passed = false;
}
else if(type == "H") {
h = new hourly(name, pay_rate, hours, type);
}
else if(type == "S") {
h = new salaried(name, pay_rate, hours, type);
}
else if(type == "F") {
h = new faculty(name, pay_rate, hours, type);
}
else if(type == "A") {
h = new administrator(name, pay_rate, hours, type);
}
if(passed == true) {
workers.push_back(h);
}
}
void campus::delete_worker() {
string name;
employee * h = NULL;
cout << "Enter name of worker to delete" << endl;
getline(cin, name);
for(unsigned int i = 0; i < workers.size(); i++) {
h = dynamic_cast<employee *>(workers[i]);
if(h->get_name() == name) {
delete h;
workers.erase(workers.begin() + i);
}
}
}
void campus::display_worker() { //allows for display of all employees or selected
string input;
employee * h = NULL;
cout << "(a)ll workers or (o)ne worker?" << endl;
cin >> input;
cin.ignore();
cout << "type // payrate // name // hours // salary" << endl;
if(input == "a") {
for(unsigned int i = 0; i < workers.size(); i++){
h = dynamic_cast<employee *>(workers[i]);
cout << *workers[i] << " $" << h->get_salary() << endl;
}
}
if(input == "o") {
cout << "name: ";
employee * h = NULL;
getline(cin, input);
for(unsigned int i = 0; i < workers.size(); i++) {
h = dynamic_cast<employee *>(workers[i]);
if(h->get_name() == input) {
cout << *h << " $" << h->get_salary() << endl;
}
}
}
}
void campus::sort_name() {
bool ready = true;
employee * h = NULL;
employee * j = NULL;
while(ready) {
for(unsigned int i = 0; i < workers.size() -1; i++) {
h = dynamic_cast<employee *>(workers[i]);
j = dynamic_cast<employee *>(workers[i+1]);
ready = false;
if(h->get_name() > j->get_name()) {
workers.push_back(workers[i]);
workers[i] = workers[i+1];
workers[i+1] = workers[workers.size()-1];
workers.pop_back();
ready = true;
}
}
}
}
void campus::sort_pay() {
bool ready = true;
employee * h = NULL;
employee * j = NULL;
while(ready) {
for(unsigned int i = 0; i < workers.size() -1; i++) {
h = dynamic_cast<employee *>(workers[i]);
j = dynamic_cast<employee *>(workers[i+1]);
ready = false;
if(h->get_payrate() > j->get_payrate()) {
workers.push_back(workers[i]);
workers[i] = workers[i+1];
workers[i+1] = workers[workers.size()-1];
workers.pop_back();
ready = true;
}
}
}
}
void campus::sort_worker() { //allows for either sort by name or by pay
string input;
cout << "sort by (n)ame or by (p)ay?" << endl;
cin >> input;
if(input == "n") {
sort_name();
}
if(input == "p") {
sort_pay();
}
}
void campus::advance_month() {
employee * h = NULL;
for(unsigned int i = 0; i < workers.size(); i++) {
h = dynamic_cast<employee *>(workers[i]);
h->reset_hours();
}
}
void campus::set_hours() {
string name;
employee * h = NULL;
cout << "enter name of employee" << endl;
getline(cin, name);
for(unsigned int i = 0; i < workers.size(); i++) {
h = dynamic_cast<employee *>(workers[i]);
if(h->get_name() == name) {
int input;
cout << "enter hours" << endl;
cin >> input;
cin.ignore();
h->set_hours(input);
}
}
}
void campus::add_files(campus c) { //function for i/o. can either write to a file or take a file in
string add_or_write;
cout << "(a)dd or (w)rite to file?" << endl;
cin >> add_or_write;
cin.ignore();
if(add_or_write == "a") {
bool file_correct = false;
string input, input_file_name;
while(!file_correct) {
cout << "please enter file name: ";
getline(cin, input);
ifstream inputs(input.c_str());
if(inputs.good()) {
input_file_name = input;
file_correct = true;
string lineread;
while(getline(inputs, lineread)) {
bool worked;
string name, type;
double pay_rate;
worked = parse_n_load(lineread, name, type, pay_rate);
if(worked == true) {
add_worker_from_parse(name, type, pay_rate);
}
lineread = "";
}
}
else {
cerr << "incorrect file name" << endl;
}
}
}
if(add_or_write == "w") {
bool file_correct = false;
string input, input_file_name;
string output_file_name;
file_correct = false;
while(!file_correct) {
cout << "please enter file name: ";
getline(cin, output_file_name);
ofstream out(output_file_name.c_str());
if(out.good()) {
out << c;
file_correct = true;
}
else {
cerr << "incorrect file name" << endl;
}
}
}
}
ostream & operator<<(ostream & os, campus & t) { //makes writing out to files much easier
employee * h = NULL;
for(unsigned int i = 0; i < t.workers.size(); i++) {
h = dynamic_cast<employee *>(t.workers[i]);
os << h->get_type() << " " << h->get_payrate() << " " << h->get_name() << "\n";
}
return os;
}

27
cs142/final/campus.h Normal file
View File

@ -0,0 +1,27 @@
#ifndef __CAMPUS_H__
#define __CAMPUS_H__
#include "employee.h"
#include <vector>
using namespace std;
class campus {
private:
vector<employee*> workers;
public:
void add_worker();
void add_worker_from_parse(string name, string type, double pay_rate);
void delete_worker();
void display_worker();
void sort_worker();
void advance_month();
void set_hours();
void add_files(campus c);
void sort_name();
void sort_pay();
bool contains(string name);
friend ostream & operator<<(ostream & os, campus & t);
};
#endif

35
cs142/final/employee.cpp Normal file
View File

@ -0,0 +1,35 @@
#include "employee.h"
#include <iostream>
using namespace std;
employee::employee(string name, double pay_rate, int hours, string type) :
name(name), pay_rate(pay_rate), hours(hours), type(type) {}
string employee::get_name(){
return name;
}
double employee::get_payrate() {
return pay_rate;
}
int employee::get_hours() {
return hours;
}
string employee::get_type() {
return type;
}
void employee::reset_hours() {
hours = 0;
}
void employee::set_hours(int input) {
hours += input;
}
ostream & operator<<(ostream & os, employee & t){ //makes printing out employee easy
os << t.type << " " << t.pay_rate << " " << t.name << " " << t.hours;
return os;
}

27
cs142/final/employee.h Normal file
View File

@ -0,0 +1,27 @@
#ifndef __EMPLOYEE_H__
#define __EMPLOYEE_H__
#include <iostream>
using namespace std;
class employee {
private:
string name;
protected:
string type;
double pay_rate;
int hours;
public:
employee(string name, double pay_rate, int hours, string type);
string get_name();
double get_payrate();
string get_type();
int get_hours();
void set_hours(int input);
void reset_hours();
virtual int get_salary() = 0;
friend ostream & operator<<(ostream & os, employee & t);
};
#endif

32
cs142/final/faculty.cpp Normal file
View File

@ -0,0 +1,32 @@
#include "faculty.h"
#include "employee.h"
#include <cstdlib>
#include <iostream>
using namespace std;
faculty::faculty(string name, double pay_rate, int hours, string type) : employee(name, pay_rate, hours, type),
grad_students(set_grad_students()) {}
int faculty::get_salary() {
double pay_rate_return = 0;
if(grad_students > 0){
double percent;
pay_rate_return = pay_rate;
for(int i = 0; i < grad_students; i++){
percent += 0.05;
}
pay_rate_return += pay_rate*percent;
return pay_rate_return;
}
return pay_rate;
}
int faculty::get_grad_students() {
return grad_students;
}
int faculty::set_grad_students() { //gets random number of grad students for faculty
srand(time(NULL));
int students = rand() % 5;
return students;
}

19
cs142/final/faculty.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef __FACULTY_H__
#define __FACULTY_H__
#include <iostream>
#include "employee.h"
using namespace std;
class faculty : public employee {
private:
int grad_students;
public:
faculty(string name, double pay_rate, int hours, string type);
int get_grad_students();
int set_grad_students();
int get_salary();
};
#endif

19
cs142/final/hourly.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "hourly.h"
#include "employee.h"
using namespace std;
hourly::hourly(string name, double pay_rate, int hours, string type) : employee(name, pay_rate, hours, type) {}
int hourly::get_salary() {
int salary;
int overtime;
if((hours - 170) > 0) {
overtime = (hours - 170);
salary = 170 * pay_rate;
salary += overtime * (pay_rate * 1.5);
return salary;
}
salary = hours * pay_rate;
return salary;
}

15
cs142/final/hourly.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef __HOURLY_H__
#define __HOURLY_H__
#include <iostream>
#include "employee.h"
using namespace std;
class hourly : public employee {
public:
hourly(string name, double pay_rate, int hours, string type);
int get_salary();
};
#endif

48
cs142/final/main.cpp Normal file
View File

@ -0,0 +1,48 @@
#include <iostream>
#include <fstream>
#include "employee.h"
#include "salaried.h"
#include "hourly.h"
#include "faculty.h"
#include "administrator.h"
#include "util.h"
#include "campus.h"
using namespace std;
int main() { //driver for program
campus c = campus();
bool keep_going = true;
while(keep_going) {
string input;
cout << "(a)dd worker, (r)emove worker, (d)isplay worker, add (h)ours, \n";
cout << " (s)ort workers, advance (m)onth, add (f)ile, (q)uit" << endl;
cin >> input;
cin.ignore();
if(input == "a") {
c.add_worker();
}
if(input == "r") {
c.delete_worker();
}
if(input == "h") {
c.set_hours();
}
if(input == "d") {
c.display_worker();
}
if(input == "s") {
c.sort_worker();
}
if(input == "m") {
c.advance_month();
}
if(input == "f") {
c.add_files(c); //will either take in a file or write out to one
}
if(input == "q") {
keep_going = false;
}
}
}

13
cs142/final/salaried.cpp Normal file
View File

@ -0,0 +1,13 @@
#include "salaried.h"
#include "employee.h"
using namespace std;
salaried::salaried(string name, double pay_rate, int hours, string type) : employee(name, pay_rate, hours, type) {}
int salaried::get_salary() {
if(hours > 170/2) {
return pay_rate;
}
return 0;
}

15
cs142/final/salaried.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef __SALARIED_H__
#define __SALARIED_H__
#include <iostream>
#include "employee.h"
using namespace std;
class salaried : public employee {
public:
salaried(string name, double pay_rate, int hours, string type);
int get_salary();
};
#endif

46
cs142/final/tags Normal file
View File

@ -0,0 +1,46 @@
!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/
!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/
!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/
!_TAG_PROGRAM_NAME Exuberant Ctags //
!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/
!_TAG_PROGRAM_VERSION 5.9~svn20110310 //
CXXFLAGS Makefile /^CXXFLAGS= -Wall -g$/;" m
EXE Makefile /^EXE=main$/;" m
OBJECTS Makefile /^OBJECTS=main.o employee.o hourly.o salaried.o administrator.o faculty.o util.o$/;" m
__ADMINISTRATOR_H__ administrator.h 2;" d
__EMPLOYEE_H__ employee.h 2;" d
__FACULTY_H__ faculty.h 2;" d
__HOURLY_H__ hourly.h 2;" d
__SALARIED_H__ salaried.h 2;" d
__UTIL_H__ util.h 2;" d
administrator administrator.cpp /^administrator::administrator(string name, double pay_rate, int hours) : employee(name, pay_rate, hours) {}$/;" f class:administrator
administrator administrator.h /^class administrator : public employee {$/;" c
employee employee.cpp /^employee::employee(string name, double pay_rate, int hours) :$/;" f class:employee
employee employee.h /^class employee {$/;" c
faculty faculty.cpp /^faculty::faculty(string name, double pay_rate, int hours) : employee(name, pay_rate, hours),$/;" f class:faculty
faculty faculty.h /^class faculty : public employee {$/;" c
get_grad_students faculty.cpp /^int faculty::get_grad_students() {$/;" f class:faculty
get_hours employee.cpp /^int employee::get_hours() {$/;" f class:employee
get_name employee.cpp /^string employee::get_name(){$/;" f class:employee
get_payrate employee.cpp /^double employee::get_payrate() {$/;" f class:employee
get_salary administrator.cpp /^int administrator::get_salary() {$/;" f class:administrator
get_salary faculty.cpp /^int faculty::get_salary() {$/;" f class:faculty
get_salary hourly.cpp /^int hourly::get_salary() {$/;" f class:hourly
get_salary salaried.cpp /^int salaried::get_salary() {$/;" f class:salaried
grad_students faculty.h /^ int grad_students;$/;" m class:faculty
hourly hourly.cpp /^hourly::hourly(string name, double pay_rate, int hours) : employee(name, pay_rate, hours) {}$/;" f class:hourly
hourly hourly.h /^class hourly : public employee {$/;" c
hours employee.h /^ int hours;$/;" m class:employee
main main.cpp /^int main() {$/;" f
name employee.h /^ string name;$/;" m class:employee
parse_n_load util.cpp /^bool parse_n_load(const string & input, string & name, string & type,$/;" f
pay_rate employee.h /^ double pay_rate;$/;" m class:employee
salaried salaried.cpp /^salaried::salaried(string name, double pay_rate, int hours) : employee(name, pay_rate, hours) {}$/;" f class:salaried
salaried salaried.h /^class salaried : public employee {$/;" c
set_grad_students faculty.cpp /^int faculty::set_grad_students() {$/;" f class:faculty
test_admin main.cpp /^void test_admin() {$/;" f
test_faculty main.cpp /^void test_faculty() {$/;" f
test_hourly main.cpp /^void test_hourly() {$/;" f
test_salaried main.cpp /^void test_salaried() {$/;" f
test_util main.cpp /^void test_util() {$/;" f
tokenize util.cpp /^vector<string> tokenize(const string & str, const string & delimiters) {$/;" f

4
cs142/final/test.txt Normal file
View File

@ -0,0 +1,4 @@
A 10.5 zombie
alka alkjsa
F 152 stephen is awesome
H 15.243 cremeballs. creame

46
cs142/final/util.cpp Normal file
View File

@ -0,0 +1,46 @@
#include <vector>
#include <string>
using namespace std;
#include <cstdlib>
#include "util.h"
#include <iostream>
vector<string> tokenize(const string & str, const string & delimiters) {
//tokenizes a string by the delimiter passed in
vector<string> tokens;
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos or string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
bool parse_n_load(const string & input, string & name, string & type,
double & pay_rate) {
vector<string> tokens = tokenize(input);
if(tokens.size() == 0) {
return false;
}
type = tokens[0];
if (not ( type == "A"
or type == "F"
or type == "H"
or type == "S")) {
return false;
}
pay_rate = atof(tokens[1].c_str());
if(pay_rate == 0) {
return false;
}
for(unsigned int i = 2; i < tokens.size(); i++) {
name += tokens[i];
if(i < tokens.size() - 1) {
name += " ";
}
}
return true;
}

14
cs142/final/util.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef __UTIL_H__
#define __UTIL_H__
#include <string>
#include <vector>
using namespace std;
void print(const string & in);
vector<string> tokenize(const string & str, const string & delimiters=" ");
bool parse_n_load(const string & input, string & name, string & type,
double & pay_rate);
#endif

6
cs142/lab00/Makefile Normal file
View File

@ -0,0 +1,6 @@
CPPFLAGS=-Wall -g -std=c++0x
all: hello_world
clean:
rm -rv hello_world

View File

@ -0,0 +1,10 @@
#include <iostream>
using namespace std;
int main() {
cout << "Hello, world! My name is Derek McQuay."<< endl;
cin.get();
return 0;
}

17
cs142/lab01/byu.cpp Normal file
View File

@ -0,0 +1,17 @@
#include <iostream>
using namespace std;
int main() {
cout << " Basic BYU Trivia\n" << endl;
cout << " Questions Answers \n" << endl;
cout << "What was the original name of BYU? Brigham Young Academy" << endl;
cout << "When was BYA established? 1875" << endl;
cout << "Who was the first \"permanent\" principal of BYA? Karl G. Maeser" << endl;
cout << "When did BYA become BYU? 1903" << endl;
cout << "To what sports conference do we belong? Mountain West Conference(MWC)" << endl;
cout << "When did BYU win the national football title? 1984" << endl;
cout << "Who won the Heisman Trophy in 1990? Ty Detmer" << endl;
}

22
cs142/lab01/quiz.txt Normal file
View File

@ -0,0 +1,22 @@
A
D
B
A
B
C
B
B
B
B
D
B
B
C
A
C
D
A,C
B
B
A,B,C,D
so we can learn by doing rather than let someone else learn.

10
cs142/lab02/Makefile Normal file
View File

@ -0,0 +1,10 @@
CPPFLAGS=-Wall -g -std=c++0x
all: timer temperature binary
binary: binary.cpp
temperature: temperature.cpp
timer: timer.cpp
clean:
rm -rv timer temperature binary

57
cs142/lab02/binary.cpp Normal file
View File

@ -0,0 +1,57 @@
#include <iostream>
#include <vector>
using namespace std;
int main() {
int value;
int first, second, third, fourth, fifth;
vector<int> final;
cout << "please insert your number between 0 and 31" << endl;
cin >> value;
int prin = value%2;
value = value/2;
if(prin >=1)
first = 1;
else
first = 0;
final.push_back(first);
prin = value%2;
value = value/2;
if(prin >=1)
second = 1;
else
second = 0;
final.push_back(second);
prin = value%2;
value = value/2;
if(prin >= 1)
third = 1;
else
third = 0;
final.push_back(third);
prin = value%2;
value = value/2;
if(prin >= 1)
fourth = 1;
else
fourth = 0;
final.push_back(fourth);
prin = value%2;
value = value/2;
if(prin >= 1)
fifth = 1;
else
fifth = 0;
final.push_back(fifth);
cout <<fifth<<fourth<<third<<second<<first << endl;
// for(unsigned int i = 0 ; i<final.size();i++) {
// cout << final[i];
// }
cout << "\n";
}

View File

@ -0,0 +1,20 @@
#include <iostream>
using namespace std;
int main() {
double temperature;
cout << "please enter a temperature in degress Fahrenheit:" << endl;
cin >> temperature;
double celsius = (temperature-32) * 5/9;
cout << "This is Fahrenheit as an int:" << endl;
cout << (int) temperature << endl;
cout << "This is Celsius as a double:" << endl;
cout << celsius << endl;
cout << "This is Celsius as an int:" << endl;
cout << (int) celsius << endl;
}

30
cs142/lab02/timer.cpp Normal file
View File

@ -0,0 +1,30 @@
#include <iostream>
#include <cmath>
using namespace std;
void calculate (int a) {
int hours, minutes, seconds;
hours = (a / 3600);
minutes = (a / 60) - (hours * 60);
seconds = a % 60;
cout << "hours: " << hours << " minutes: " << minutes << " seconds: " << seconds << endl;
};
int main() {
int time;
cout << "please enter a number of seconds" << endl;
cin >> time;
cout << time << endl;
cout << "absolute value of input " << abs (time) << endl;
calculate(time);
cout << "now with sqrt: " << endl;
calculate(sqrt(time));
}

4
cs142/lab03/Makefile Normal file
View File

@ -0,0 +1,4 @@
CXXFLAGS=-Wall -g -std=c++0x
all: grade
clean:
rm -vf grade

View File

@ -0,0 +1,13 @@
#include <iostream>
using namespace std;
#include "person.h"
#pragma once
int main(int argc, char * argv[]) {
person p;
p.get_grades();
}

View File

@ -0,0 +1,60 @@
using namespace std;
#include "person.h"
#pragma once
void person::get_latedays() {
cout << "Please enter if it was turned in earlier or late (earlier with a negative number): " << endl;
cin >> late_days;
total_latedays = total_latedays + late_days;
}
void person::get_exam_latedays(){
cout << "Please enter if it was turned in in late (number of late days): " << endl;
cin >> late_days_exam;
late_days_exam = abs(late_days_exam);
total_latedays_exam = total_latedays_exam + late_days_exam;
}
void person::calculate_grade() {
grade = lab1 + lab2 + lab3 + lab4 + lab5 + lab6 + lab7 + lab8 + lab9 + lab10 + lab11 + exam1 + exam2 + final;
}
void person::get_grades(){
cout << "please enter the name of the student: " << endl;
cout << "now we are going to enter the following grades for the student: " << endl;
cout << "Grade for lab 01: " << endl;
cin >> lab1;
cout << "Grade for lab 02; " << endl;
cin >> lab2;
cout << "Grade for lab 03; " << endl;
cin >> lab3;
cout << "Grade for lab 04; " << endl;
cin >> lab4;
cout << "Grade for lab 05; " << endl;
cin >> lab5;
cout << "Grade for lab 06; " << endl;
cin >> lab6;
cout << "Grade for lab 07; " << endl;
cin >> lab7;
cout << "Grade for lab 08; " << endl;
cin >> lab8;
cout << "Grade for lab 09; " << endl;
cin >> lab9;
cout << "Grade for lab 10; " << endl;
cin >> lab10;
cout << "Grade for lab 11; " << endl;
cin >> lab11;
cout << "Grade for exam 1: " << endl;
cin >> exam1;
cout << "Grade for exam 2: " << endl;
cin >> exam2;
cout << "Grade for final: " << endl;
cin >> final;
cout << "Please enter how many days late the final was: " << endl;
}

View File

@ -0,0 +1,24 @@
#include <iostream>
#include <cmath>
using namespace std;
class person
{
private:
string person_name;
int lab1, lab2, lab3, lab4, lab5, lab6, lab7, lab8, lab9, lab10, lab11, exam1, exam2, final;
int late_days, total_latedays, late_days_exam, total_latedays_exam;
int grade;
public:
person(){};
void get_latedays();
void get_exam_latedays();
void calculate_grade();
void get_grades();
};

304
cs142/lab03/grade.cpp Normal file
View File

@ -0,0 +1,304 @@
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
struct student {
string name;
int grade;
string letter_grade;
};
int main() {
// this is incorrect: typedef struct student1;
struct student student1;
struct student student2;
int lab1, lab2, lab3, lab4, lab5, lab6, lab7, lab8, lab9, lab10, lab11;
int exam1, exam2, final;
int late_days;
int late_daytotal = 0;
int exam_late_days;
int exam_late_days_total = 0;
string name;
for(int i = 1; i<3; i++){
cout << "Please enter name of student: " << endl;
cin >> name;
cout << "Please enter grade for lab 1: " << endl;
cin >> lab1;
if(lab1 >20 or lab1 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-2 or late_days > 2){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 2: " << endl;
cin >> lab2;
if(lab2 >20 or lab2 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-2 or late_days > 2){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 3: " << endl;
cin >> lab3;
if(lab3 >30 or lab3 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-3 or late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 4: " << endl;
cin >> lab4;
if(lab4 >30 or lab4 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-3 or late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 5: " << endl;
cin >> lab5;
if(lab5 >30 or lab5 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-3 or late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 6: " << endl;
cin >> lab6;
if(lab6 >30 or lab6 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-3 or late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 7: " << endl;
cin >> lab7;
if(lab7 >30 or lab7 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-3 or late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 8: " << endl;
cin >> lab8;
if(lab8 >30 or lab8 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-3 or late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 9: " << endl;
cin >> lab9;
if(lab9 >20 or lab9 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-2 or late_days > 2){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 10: " << endl;
cin >> lab10;
if(lab10 >20 or lab10 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-2 or late_days > 2){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter grade for lab 11: " << endl;
cin >> lab11;
if(lab11 >40 or lab11 < 0){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?: (indicate early days by negative number, late days by positive" << endl;
cin >> late_days;
if(late_days <-4 or late_days > 4){
cout << "This is not in the range!" << endl;
return 0;
}
late_daytotal = late_daytotal + late_days;
cout << "Please enter exam 1 score: " << endl;
cin >> exam1;
if(exam1 < 0 or exam1 > 100){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?" << endl;
cin >> exam_late_days;
if(exam_late_days < 0 or exam_late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
exam_late_days_total = exam_late_days_total + exam_late_days;
cout << "Please enter exam 2 score: " << endl;
cin >> exam2;
if(exam2 < 0 or exam2 > 100){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?" << endl;
cin >> exam_late_days;
if(exam_late_days < 0 or exam_late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
exam_late_days_total = exam_late_days_total + exam_late_days;
cout << "Please enter final score: " << endl;
cin >> final;
if(final < 0 or final > 100){
cout << "This is not in the range!" << endl;
return 0;
}
cout << "Were there late days/early days?" << endl;
cin >> exam_late_days;
if(exam_late_days < 0 or exam_late_days > 3){
cout << "This is not in the range!" << endl;
return 0;
}
exam_late_days_total = exam_late_days_total + exam_late_days;
int total_labs = lab1+lab2+lab3+lab4+lab5+lab6+lab7+lab8+lab9+lab10+lab11;
int total_exam = exam1 + exam2 + final;
int final_grade = total_labs + total_exam;
if(late_daytotal < 0){
final_grade = final_grade + abs(late_daytotal);
}
else{
final_grade = final_grade - late_daytotal;
}
final_grade = final_grade - exam_late_days_total*20;
string letter_grade;
if(final_grade >= 570)
letter_grade = "A";
if(final_grade <570 && final_grade >=540)
letter_grade = "A-";
if(final_grade < 540 && final_grade >= 522)
letter_grade = "B+";
if(final_grade < 522 && final_grade >= 498)
letter_grade = "B";
if(final_grade < 498 && final_grade >= 480)
letter_grade = "B-";
if(final_grade < 480 && final_grade >= 462)
letter_grade = "C+";
if(final_grade < 462 && final_grade >= 438)
letter_grade = "C";
if(final_grade < 438 && final_grade >= 420)
letter_grade = "C-";
if(final_grade < 420 && final_grade >= 402)
letter_grade = "D+";
if(final_grade < 402 && final_grade >= 378)
letter_grade = "D";
if(final_grade < 378 && final_grade >= 360)
letter_grade = "D-";
if(final_grade < 360)
letter_grade = "E";
// something looks iffy here: (check your warnings (read all the words (even 'assignment')))
if (i == 1) {
student1.name = name;
student1.grade = final_grade;
student1.letter_grade = letter_grade;
}
else {
student2.name = name;
student2.grade = final_grade;
student2.letter_grade = letter_grade;
}
}
int order = 0;
cout << "Please enter what order you want to see the students: " << endl;
cout << "enter 1 for alphabetical or 2 for highest score first: " << endl;
cin >> order;
if(order > 2 or order < 1) {
cout << "out of range" <<endl;
return 0;
}
if(order == 1){
if(student1.name < student2.name) {
cout << "name " << student1.name << endl;
cout << "points " << student1.grade << endl;
cout << "letter grade " << student1.letter_grade << endl;
cout << "name " << student2.name << endl;
cout << "points " << student2.grade << endl;
cout << "letter grade " << student2.letter_grade << endl;
}
else {
cout << "name " << student2.name << endl;
cout << "points " << student2.grade << endl;
cout << "letter grade " << student2.letter_grade << endl;
cout << "name " << student1.name << endl;
cout << "points " << student1.grade << endl;
cout << "letter grade " << student1.letter_grade << endl;
}
}
if(order == 2){
if(student1.grade > student2.grade){
cout << "name " << student1.name << endl;
cout << "points " << student1.grade << endl;
cout << "letter grade " << student1.letter_grade << endl;
cout << "name " << student2.name << endl;
cout << "points " << student2.grade << endl;
cout << "letter grade " << student2.letter_grade << endl;
}
else {
cout << "name " << student2.name << endl;
cout << "points " << student2.grade << endl;
cout << "letter grade " << student2.letter_grade << endl;
cout << "name " << student1.name << endl;
cout << "points " << student1.grade << endl;
cout << "letter grade " << student1.letter_grade << endl;
}
}
}

16
cs142/lab03/quick.cpp Normal file
View File

@ -0,0 +1,16 @@
#include <iostream>
#include <string>
using namespace std;
int main () {
string a, b;
cin >> a;
cin >> b;
if(a<b)
cout << "first is before last" << endl;
else
cout << "Second is before first" << endl;
}

59
cs142/lab03/test.txt Normal file
View File

@ -0,0 +1,59 @@
derek
20
-2
20
-2
30
-2
30
-2
30
-2
30
-2
30
-2
30
0
20
0
20
0
40
0
100
2
0
0
100
0
alex
20
-2
20
1
30
1
30
1
30
1
30
1
30
0
30
0
20
0
20
0
40
0
100
0
100
0
100
1
1

7
cs142/lab04/Makefile Normal file
View File

@ -0,0 +1,7 @@
CXXFLAGS=-Wall -g -std=c++0x
all: number
clean:
rm -vf number
test: all
./number

53
cs142/lab04/loops.py Normal file
View File

@ -0,0 +1,53 @@
import random
import time
def get_numbers(pow2, compliment):
numbers = []
constant = compliment
for i in (0, 1):
for j in (0, 1):
for k in (0, 1):
for l in (0, 1):
if pow2 == 0:
cur_digits = (i, j, k, l, constant)
if pow2 == 1:
cur_digits = (i, j, k, constant, l)
if pow2 == 2:
cur_digits = (i, j, constant, k, l)
if pow2 == 3:
cur_digits = (i, constant, j, k, l)
if pow2 == 4:
cur_digits = (constant, i, j, k, l)
numbers.append(cur_digits)
return numbers
print "example of how to use randomness to determine compliment"
a_few_tries = xrange(3)
for i in a_few_tries:
compliment = random.randint(0, 3026) % 2
for i in get_numbers(pow2=0, compliment=compliment):
print i
print "for loop to print out all numbers from 2^0 to 2^5"
for i in (0, 1):
for j in (0, 1):
for k in (0, 1):
for l in (0, 1):
for m in (0, 1):
for n in (0, 1):
print i, j, k, l, m
print "example function to convert a string in binary to integers: (see source)"
def bin2int(s):
total = 0
for i in xrange(len(s)):
if s[i] == '1':
total += 2**(len(s) - i - 1)
return total
print "here I test out the bin2int func defined above:"
test_cases = ('1010', '1011', '0100', '1000', '0111')
for test in test_cases:
print test, bin2int(test), int(test, 2)

111
cs142/lab04/number.cpp Normal file
View File

@ -0,0 +1,111 @@
#include <iostream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include <sstream>
#include <cmath>
#include <algorithm>
using namespace std;
int bit2dec(string s);
vector<int> get_numbers(int pow, int compliment) {
string store;
vector<int> numbers;
int constant = compliment;
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
for(int k = 0; k < 2; k++){
for(int l = 0; l < 2; l++){
ostringstream stream;
if(pow == 0){
stream << i << j << k << l << constant;
}
else if(pow == 1){
stream << i << j << k << constant << l;
}
else if(pow == 2){
stream << i << j << constant << k << l;
}
else if(pow == 3){
stream << i << constant << j << k << l;
}
else if(pow == 4){
stream << constant << i << j << k << l;
}
store = stream.str();
numbers.push_back(bit2dec(store));
}
}
}
}
return numbers;
}
ostream & operator<<(ostream & os, const vector<int> & nums) {
for(unsigned int i = 0; i < nums.size(); i++){
if(i % 4 == 0){
os << endl;
}
os << nums[i] << " ";
}
return os;
}
int bit2dec(string s) {
int total = 0;
int power = 0;
for(int i = s.size() - 1; i >= 0; i--) {
if(s[i] == '1') {
total += pow(2,power);
}
power++;
}
return total;
}
int main() {
srand (time(NULL));
int keep_playing = 0;
while(keep_playing == 0){
ostringstream answer;
for(unsigned int i = 0; i < 5 ; i++) {
int switcher = rand() % 2;
string check;
cout << "Is your number in this list? enter y for yes n for no" << endl;
cout << get_numbers(i, switcher) << endl;
cin >> check;
if(switcher == 0){
if(check == "y") {
answer << '0';
}
else {
answer << '1';
}
}
if(switcher == 1) {
if(check == "y") {
answer << '1';
}
else {
answer << '0';
}
}
}
string final = answer.str();
reverse (final.begin(), final.end());
cout << bit2dec(final) << endl;
cout << "Do you want to keep playing? enter y for yes, n for no" << endl;
string check;
cin >> check;
if(check == "n"){
keep_playing++;
}
}
return 0;
}

17
cs142/lab04/quick.cpp Normal file
View File

@ -0,0 +1,17 @@
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> numbers;
numbers.push_back(0);
numbers.push_back(1);
numbers.push_back(0);
numbers.push_back(1);
numbers.push_back(0);
cout << numbers[0] << numbers[1]<< numbers[2]<<numbers[3] << numbers[4] <<endl;
}

10
cs142/lab05/Makefile Normal file
View File

@ -0,0 +1,10 @@
CXXFLAGS=-Wall -g -std=c++0x
all: monopoly
clean:
rm -vf monopoly
test: all
./monopoly
debug: all
gdb monopoly

10
cs142/lab05/game/Makefile Normal file
View File

@ -0,0 +1,10 @@
CXXFLAGS=-Wall -g -std=c++0x
all: monopoly
clean:
rm -vf monopoly
test: all
./monopoly
debug: all
gdb monopoly

18
cs142/lab05/game/game.cpp Normal file
View File

@ -0,0 +1,18 @@
#include <iostream>
#include <vector>
using namespace std;
struct property {
string name;
int value;
}
void create_board(vector<property> & board) {
board.push_back(property{"mediterranean Avenue", 60}
}
int main() {
vector<property> board;
cout << board.name << endl;
}

View File

@ -0,0 +1,175 @@
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <vector>
using namespace std;
struct property{
string name;
int value;
};
void roll_the_dice() {
srand(time(NULL));
int roll = rand() % 6 +1;
int roll2 = rand() % 6 +1;
cout << roll << " + "<< roll2 << " equals " << roll +roll2 << endl;
}
void report_current_money(int & current_money) {
cout << "this is your current money" << endl;
cout << current_money << endl;
}
void add_money(int & current_money) {
cout << "how much money would you like to add? " << endl;
int add;
cin >> add;
if(add < 0){
cout << "please enter a positive number" << endl;
add_money(current_money);
}
else {
current_money += add;
cout << current_money << endl;
}
}
void spend_money(int & current_money) {
cout << "how much money would you like to spend? " << endl;
int minus;
cin >> minus;
if(current_money - minus < 0) {
cout << "This would result in a negative number!" << endl;
}
else {
current_money -= minus;
cout << current_money << endl;
}
}
void pass_go(int & current_money) {
cout << "you passed go, collect 200 dollars!" << endl;
current_money += 200;
}
bool has_property(vector<property> & props, string name) {
bool has_prop = false;
for(unsigned int i = 0; i < props.size(); i++) {
if(name == props[i].name) {
has_prop = true;
}
}
return has_prop;
}
void buy_property(vector<property> & properties, int & current_money) {
bool success = false;
int property_value = 0;
string input_name;
while(!success) {
cout << "please enter property name: ";
cin >> input_name;
if (not has_property(properties, input_name) ){
cout << "What is the value of your property?" << endl;
cin >> property_value;
while(property_value < 0) {
cout << "incorrect property value. Please try again." << endl;
cin >> property_value;
}
if(current_money - property_value < 0) {
cout << "you dont have enough money to purchase this." << endl;
break;
}
current_money -= property_value;
properties.push_back(property{input_name, property_value});
success = true;
}
else {
cerr << "you already have that property" << endl;
break;
}
}
}
void sell_property(vector<property> & properties, int & current_money) {
string property_to_sell;
cout << "please enter the property name you would like to sell: " << endl;
cin >> property_to_sell;
if(has_property(properties, property_to_sell)) {
for(unsigned int i = 0; i < properties.size(); i++) {
if(properties[i].name == property_to_sell) {
current_money += properties[i].value;
properties.erase(properties.begin()+i);
}
}
}
else {
cout << "you dont own that property to be able to sell it" << endl;
}
}
void quit_game() {
cout << "thanks for playing!" << endl;
exit (0);
}
ostream & operator<<(ostream & os, const property & prop) {
os << "{name: '" << prop.name
<< "', value: " << prop.value
<< "}";
return os;
}
void display_properties(vector<property> & properties) {
cout << "found the following "
<< properties.size() << " properties:" << endl;
for(unsigned int i = 0; i < properties.size(); i++) {
cout << properties[i] << endl;
}
}
void play_game(vector<property> & properties, int & current_money) {
bool keep_playing = true;
while(keep_playing){
int choice;
cout << "Welcome to Monopoly" << endl;
cout << "please enter a number correspoding to what function you would like to run" << endl;
cout << "1) Roll the dice\n2) Report the player's current money\n3) Add money\n4) Spend money" << endl;
cout << "5) Pass GO\n6) Buy Property\n7)Sell Property\n8)Display owned properties\n9) Quit the program" << endl;
cin >> choice;
if(choice == 1)
roll_the_dice();
else if(choice == 2)
report_current_money(current_money);
else if(choice == 3)
add_money(current_money);
else if(choice == 4)
spend_money(current_money);
else if(choice == 5)
pass_go(current_money);
else if(choice == 6)
buy_property(properties, current_money);
else if(choice == 7)
sell_property(properties, current_money);
else if(choice == 8)
display_properties(properties);
else if(choice == 9)
quit_game();
}
}
int main() {
int current_money = 1500;
vector<property> properties;
play_game(properties, current_money);
return 0;
}

View File

@ -0,0 +1,40 @@
Mediterranean Avenue -60
Community Chest
Baltic Avenue - 60
Income Tax
Reading Railroad - 200
Oriental Avenue - 100
Chance
Vermont Avenue - 100
Connecticut Avenue - 120
Jail
St. Charles Place - 140
Electric Company - 150
States Avenue - 140
Virginia Avenue - 160
Pennsylvania Railroad - 200
St. James Place - 180
Community Chest
Tennessee Avenue - 180
New York Avenue - 200
Free parking
Kentucky Avenue - 220
Chance
Indiana Avenue - 220
Illinois Avenue - 240
B&O Railroad - 200
Atlantic Avenue - 260
Ventnor Avenue - 260
Water Works - 150
Marvin Gardens - 280
Go to jail
Pacific avenue - 300
North Carolina Avenue - 300
Community chest
Pennsylvania Avenue - 320
Short line - 200
Chance
Park Place - 350
Luxury tax
Boardwalk - 400
Go

182
cs142/lab05/monopoly.cpp Normal file
View File

@ -0,0 +1,182 @@
#include <iostream>
#include <cstdlib>
#include <vector>
using namespace std;
struct property{
string name;
int value;
};
void roll_the_dice() {
srand(time(NULL));
int roll = rand() % 6 +1;
int roll2 = rand() % 6 +1;
cout << roll << " + "<< roll2 << " equals " << roll +roll2 << endl;
}
void report_current_money(int & current_money) {
cout << "this is your current money" << endl;
cout << current_money << endl;
}
void add_money(int & current_money) {
cout << "how much money would you like to add? " << endl;
int add;
cin >> add;
if(add < 0){
cout << "please enter a positive number" << endl;
add_money(current_money);
}
else {
current_money += add;
cout << current_money << endl;
}
}
void spend_money(int & current_money) {
cout << "how much money would you like to spend? " << endl;
int minus;
cin >> minus;
if(current_money - minus < 0) {
cout << "This would result in a negative number!" << endl;
}
else {
current_money -= minus;
cout << current_money << endl;
}
}
void pass_go(int & current_money) {
cout << "you passed go, collect 200 dollars!" << endl;
current_money += 200;
}
bool has_property(vector<property> & props, string name) {
bool has_prop = false;
for(unsigned int i = 0; i < props.size(); i++) {
if(name == props[i].name) {
has_prop = true;
}
}
return has_prop;
}
void buy_property(vector<property> & properties, int & current_money) {
bool success = false;
int property_value = 0;
string input_name;
while(!success) {
cout << "please enter property name: ";
cin >> input_name;
if (not has_property(properties, input_name) ){
cout << "What is the value of your property?" << endl;
cin >> property_value;
while(property_value < 0) {
cout << "incorrect property value. Please try again." << endl;
cin >> property_value;
}
if(current_money - property_value < 0) {
cout << "you dont have enough money to purchase this." << endl;
break;
}
current_money -= property_value;
properties.push_back(property{input_name, property_value});
success = true;
}
else {
cerr << "you already have that property" << endl;
break;
}
}
}
void sell_property(vector<property> & properties, int & current_money) {
string property_to_sell;
cout << "please enter the property name you would like to sell: " << endl;
cin >> property_to_sell;
if(has_property(properties, property_to_sell)) {
for(unsigned int i = 0; i < properties.size(); i++) {
if(properties[i].name == property_to_sell) {
cout << "enter value for sale" << endl;
int sale;
cin >> sale;
if(sale < 0){
cout << "can't be nagative" << endl;
break;
}
properties[i].value = sale;
current_money += properties[i].value;
properties.erase(properties.begin()+i);
}
}
}
else {
cout << "you dont own that property to be able to sell it" << endl;
}
}
void quit_game() {
cout << "thanks for playing!" << endl;
exit (0);
}
ostream & operator<<(ostream & os, const property & prop) {
os << "{name: '" << prop.name
<< "', value: " << prop.value
<< "}";
return os;
}
void display_properties(vector<property> & properties) {
cout << "found the following "
<< properties.size() << " properties:" << endl;
for(unsigned int i = 0; i < properties.size(); i++) {
cout << properties[i] << endl;
}
}
void play_game(vector<property> & properties, int & current_money) {
bool keep_playing = true;
while(keep_playing){
int choice;
cout << "Welcome to Monopoly" << endl;
cout << "please enter a number correspoding to what function you would like to run" << endl;
cout << "1) Roll the dice\n2) Report the player's current money\n3) Add money\n4) Spend money" << endl;
cout << "5) Pass GO\n6) Buy Property\n7)Sell Property\n8)Display owned properties\n9) Quit the program" << endl;
cin >> choice;
if(choice == 1)
roll_the_dice();
else if(choice == 2)
report_current_money(current_money);
else if(choice == 3)
add_money(current_money);
else if(choice == 4)
spend_money(current_money);
else if(choice == 5)
pass_go(current_money);
else if(choice == 6)
buy_property(properties, current_money);
else if(choice == 7)
sell_property(properties, current_money);
else if(choice == 8)
display_properties(properties);
else if(choice == 9)
quit_game();
}
}
int main() {
int current_money = 1500;
vector<property> properties;
play_game(properties, current_money);
return 0;
}

6
cs142/lab06/Makefile Normal file
View File

@ -0,0 +1,6 @@
CXXFLAGS=-Wall -g -std=c++0x
all: add-display
clean:
rm -vf add-display
test: all
./add-display

211
cs142/lab06/add-display.cpp Normal file
View File

@ -0,0 +1,211 @@
#include <iostream>
#include <array>
#include <time.h>
#include <ctime>
#include <functional>
#include <cstdlib>
#include <algorithm>
using namespace std;
void display_all_restaurants(array<string, 16> & restaurants, int & current_size) {
for(int i = 0; i <= current_size - 1; i++) {
if(i == current_size - 1) {
cout << i << "-" << restaurants[i] << endl;
}
else {
cout << i << "-" << restaurants[i] << ", ";
}
}
}
void add_a_restaurant(array<string, 16> & restaurants, int & current_size) {
string name;
bool correct_entry = true;
cout << "please enter name of restaurant: " << endl;
cin.ignore();
getline(cin, name);
if(current_size >= 16) {
cout << "The array already has 16 restaurants and you can't add anymore." << endl;
}
else {
for(int i = 0; i <= current_size - 1; i++) {
if(restaurants[i] == name) {
correct_entry = false;
}
}
if(correct_entry == true) {
restaurants[current_size] = name;
current_size++;
cout << "you added the restaurant " << name << endl;
}
else {
cout << "this restaurant is already existant" << endl;
}
}
}
void remove_a_restaurant(array<string, 16> & restaurants, int & current_size) {
string name;
bool correct_entry = false;
cout << "Please enter name of restaurant you would like to remove: " << endl;
cin.ignore();
getline(cin, name);
for(int i = 0; i <= current_size -1; i++) {
if(i == current_size && restaurants[i] == name) {
current_size--;
cout << name << " has been removed" << endl;
}
if(restaurants[i] == name) {
restaurants[i] = restaurants[current_size -1];
current_size--;
correct_entry = true;
cout << name << " has been removed" << endl;
}
}
if(correct_entry == false) {
cout << "restaurant does not exist" << endl;
}
}
void shuffle_array(array<string, 16> & restaurants, int current_size) {
random_shuffle (&restaurants[0], &restaurants[current_size]);
}
int round_counter(int current_size) {
int round;
if(current_size == 16) {
round = 4;
}
else if(current_size == 8) {
round = 3;
}
else if(current_size == 4) {
round = 2;
}
else if(current_size == 2) {
round =1;
}
return round;
}
int match_counter(int current_size) {
int match;
if(current_size == 16) {
match = 8;
}
else if(current_size == 8) {
match = 4;
}
else if(current_size == 4) {
match = 2;
}
else if(current_size == 2) {
match =1;
}
return match;
}
void begin_tournament(array<string, 16> & restaurants, int & current_size) {
bool temp_bool = true;
bool tourn_running = true;
cin.ignore();
string name;
int match = match_counter(current_size);
int round = round_counter(current_size);
int current_round = 1;
array<string,8> temp_array;
while(tourn_running == true) {
int current_match = 1;
int place = 0;
temp_bool = true;
cin.ignore();
for(int i = 0; i < current_size; i += 2) {
while(temp_bool == true) {
cout << "which restaurant: " << restaurants[i] << " or " << restaurants[i + 1] << endl;
cout << "match " << current_match << "/" << match << " Round "
<< current_round << "/" << round << endl;
getline(cin, name);
if(name == restaurants[i] or name == restaurants[i + 1]) {
if(name == restaurants[i]) {
temp_array[place] = name;
}
else {
temp_array[place] = name;
}
place ++;
temp_bool = false;
current_match++;
}
else {
cout << "invalid response " << name << endl;
}
}
temp_bool = true;
}
while(temp_bool == true) {
for(int i = 0; i < place; i++) {
restaurants[i] = temp_array[i];
}
current_size = current_size/2;
if(current_size == 1) {
cout << "this is the winner " << restaurants[0] << endl;
exit(0);
}
else {
cout << "next round of tournament" << endl;
temp_bool = false;
}
}
match = match/2;
current_round++;
}
}
void test_size(array<string,16> & restaurants, int & current_size) {
if(current_size ==2 or current_size ==4 or current_size ==8 or current_size == 16) {
cout << "you have 2^n" << endl;
begin_tournament(restaurants, current_size);
}
else {
cout << "you dont have 2^n number of restaurants, please remove or enter more" << endl;
}
}
int main() {
array<string,16> restaurants = {{
"cafe rio",
"india palace",
"panda express",
"subway",
"quiznos",
"olive garden",
"jimmy johns",
"cougareat",
}};
bool temp = true;
int current_size = 8;
srand(time(NULL));
while(temp == true) {
int input;
cout << "pick a function" << endl;
cout << "1)Display all restaurants\n2)Add a restaurant\n3)Remove a restaurant" << endl;
cout << "4)Shufflle the array\n5)Begin the tournament" << endl;
cin >> input;
if(input == 1){
display_all_restaurants(restaurants, current_size);
}
if(input == 2){
add_a_restaurant(restaurants, current_size);
}
if(input == 3){
remove_a_restaurant(restaurants, current_size);
}
if(input == 4){
shuffle_array(restaurants, current_size);
}
if(input == 5){
test_size(restaurants, current_size);
}
}
}

42
cs142/lab06/array.cpp Normal file
View File

@ -0,0 +1,42 @@
#include <iostream>
#include <array>
using namespace std;
int main() {
array<string,16> test;
for(unsigned int i = 0; i < test.size(); i++) {
string a;
cout << i << " enter name" << endl;
cin >> a;
test[i] = a;
}
int a = 0;
cout << "i++" << endl;
for(unsigned int i = 0; i < test.size(); i++) {
cout << test[i] << "-" << i << " /";
}
cout << "" << endl;
cout << "i--" << endl;
for(unsigned int i = 15; i > 0; i--) {
cout << test[i] << "-" << i << " /";
}
cout << "" << endl;
cout << test.size() << " size of thing" << endl;
cout << "" << endl;
for(unsigned int i = 0; i < test.size(); i++) {
if(test[i] == "derek") {
a = i;
}
}
for(a; a < test.size(); a++) {
int b = a;
test[a] = test[b++];
}
cout << "something happening here" << a << " is where derek is" << endl;
for(unsigned int i = 0; i < test.size(); i++) {
cout << test[i] << "-" << i << " /";
}
cout << "" << endl;
}

10
cs142/lab06/test.txt Normal file
View File

@ -0,0 +1,10 @@
derek
colleen
adeline
sylas
emmett
stephen
vanessa
mardson
4
1

29
cs142/lab07/Makefile Normal file
View File

@ -0,0 +1,29 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
SOURCES=cookies.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXE=cookie
all: $(EXE)
$(EXE): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
clean:
@rm -vf *.o
@rm -rvf *.dSYM
@rm -vf $(EXE)
run: $(EXE)
./$(EXE)
debug: $(EXE)
gdb $(EXE)
valgrind: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE)
autov: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE) < test.txt

250
cs142/lab07/cookies.cpp Normal file
View File

@ -0,0 +1,250 @@
#include <iostream>
#include <string>
using namespace std;
//-------------------------------------------------------------------------------------
string * findOrder(string * cookies[], int * size, string name);
void addOrder(string * cookies[], int * size, string new_name);
int deliverOrder(string * cookies[], int * size, string name);
bool modifyOrder(string * cookies[], int * size, string original_name, string new_name);
string displayOrders(string * cookies[], int * size);
//-------------------------------------------------------------------------------------
/*
findOrder
Returns a memory address found in the given array that references a string with the same data
as the given string. Returns null if no such string is found.
It is recommended that you use this function within your other functions. If you do not, you
must still complete this function as described above.
*/
string * findOrder(string * cookies[], int * size, string name)
{
string * r = NULL;
for(int i = 0; i < *size; i++) {
if(*cookies[i] == name) {
r = cookies[i];
break;
}
}
return r;
}
//-------------------------------------------------------------------------------------
/*
addOrder
Adds the memory address of a new string to the given array. The new string should have the
same data as that of the given string.
A string may already exist containing the same data as the given string (ie, the string
passed to this function as a parameter) and whose memory address is already stored within
the given array. In this situation, add to the array the memory address of the string that
already exists rather than creating a new string.
Update the reference of size appropriately.
*/
void addOrder(string * cookies[], int * size, string new_name) {
string * found = findOrder(cookies, size, new_name);
if(found == NULL) {
cookies[*size] = new string(new_name);
}
else {
cookies[*size] = found;
}
(*size)++;
}
//-------------------------------------------------------------------------------------
/*
deliverOrder
Removes all references to strings containing the same data as the given string and reports
the number of string references removed. The overall order of the list is unchanged.
Update the reference of size appropriately.
*/
int deliverOrder(string * cookies[], int * size, string name)
{
int removes = 0;
for(int i = 0; i < *size; i++) {
if(*cookies[i] == name) {
for(int j = i; j < *size; j++) {
cookies[j] = cookies[j+1];
}
*size = *size -1;
removes++;
i--;
}
}
return removes;
}
//-------------------------------------------------------------------------------------
/*
modifyOrder
Searches the given array for a memory address to a string that contains the same data as the
first given string.
If found, the data of the found string is changed to match the data of the second given string,
and the function returns true. If not found, the function returns false.
*/
bool modifyOrder(string * cookies[], int * size, string original_name, string new_name)
{
bool result = false;
for(int i = 0; i < *size; i++) {
if(*cookies[i] == original_name) {
*cookies[i] = new_name;
result = true;
}
}
return result;
}
//-------------------------------------------------------------------------------------
/*
displayOrders
Returns a string containing a list of names referred to in the given array.
Each index in the array represents a particular box of cookies, and there may be more than
one box for each customer. Therefore, this function's output may include the same name
multiple times.
*/
string displayOrders(string * cookies[], int * size)
{
string r = "";
for(int i = 0; i < *size; i++) {
r += *cookies[i] + ", ";
}
return r;
}
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
int getOption(int range);
string getName(string message);
//-------------------------------------------------------------------------------------
int main()
{
const int MAXIMUM_SIZE = 10;
string * cookies [MAXIMUM_SIZE] = {};
int x = 0;
int * size = &(x);
bool done = false;
while(!done)
{
//Get menu option
cout << "MENU:" << endl;
cout << "\t1. Add an order\n\t2. Deliver an order\n\t3. Modify an order\n\t4. Quit\n" << endl;
int option = getOption(4);
//Adding
if(option==1)
{
if((*size) >= MAXIMUM_SIZE)
{
cout << "The car is full; cannot add more orders" << endl;
}
else
{
string new_name = getName("Please enter the customer's name for the new order:");
addOrder(cookies, size, new_name);
cout << "Cookies added for costumer [" << new_name << "]" << endl;
}
}
//Delivering
else if(option==2)
{
string name = getName("Please enter the customer's name for the delivery:");
int delivered = deliverOrder(cookies, size, name);
cout << "Delivered " << delivered << " boxes of cookies to [" << name << "]" << endl;
}
//Modifying
else if(option==3)
{
string original_name = getName("Please enter the original customer's name:");
string new_name = getName("Please enter the new customer's name:");
bool changed = modifyOrder(cookies,size,original_name,new_name);
if(changed)
{
cout << "Changed name from [" << original_name << "] to [" << new_name << "]" << endl;
}
else
{
cout << "Could not find a customer with the name: [" << original_name << "]" << endl;
}
}
//Quitting
else if(option==4)
{
done = true;
}
cout << displayOrders(cookies, size) << endl;
}
cout << "Thank you for using the cookie tracker!" << endl;
//The following line may not work on all systems; therefore, you may change this line as needed
// system("pause");
return 0;
}
//-------------------------------------------------------------------------------------
int getOption(int range)
{
int input = 0;
bool done = false;
while(!done)
{
cout << "Please select an option:" << endl;
input = 0;
cin >> input;
cin.ignore(1000,'\n');
if(cin.fail())
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error: Invalid option" << endl;
}
else if(input < 1 || input > range)
{
cout << "Error: Invalid option number" << endl;
}
else
{
done = true;
}
}
return input;
}
//-------------------------------------------------------------------------------------
string getName(string message)
{
string input = "";
bool done = false;
while(!done)
{
cout << message << endl;
input = "";
getline(cin, input);
if(cin.fail())
{
cin.clear();
cin.ignore(1000,'\n');
cout << "Error: Invalid name" << endl;
}
else
{
done = true;
}
}
return input;
}
//-------------------------------------------------------------------------------------

18
cs142/lab07/test.txt Normal file
View File

@ -0,0 +1,18 @@
1
stephen
1
michael
1
michael
1
stephen
1
derek
3
stephen
Stephen Mardson McQuay
2
michael
2
derek
4

18
cs142/lab08/Makefile Normal file
View File

@ -0,0 +1,18 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
all: people
people: main.o person.o
g++ $(CPPFLAGS) person.o main.o -o people
main.o: main.cpp person.o person.h
person.o: person.cpp person.h
test: people
./people < test.txt
clean:
rm -fv people *.o
debug: people
gdb people

106
cs142/lab08/main.cpp Normal file
View File

@ -0,0 +1,106 @@
#include <iostream>
#include <vector>
using namespace std;
#include "person.h"
void display_list_of_friends(vector<person> & p) {
for(unsigned int i = 0; i < p.size(); i++) {
cout << p[i].name << endl;
cout << "\t" << p[i].fav_food << endl;
cout << "\tlist of friends: " << endl;
for(unsigned int j = 0; j < p[i].friends.size(); j++) {
cout << "\t\t" << p[i].friends[j] << endl;;
}
}
}
int get_person(vector<person> & p, string name) {
int position = -1;
for(unsigned int i = 0; i < p.size(); i++) {
if(p[i].name == name) {
position = i;
break;
}
}
return position;
}
int main() {
vector<person> people;
string selection;
while(1) {
cout << "1)add person\n2)display all people\n3)add friend\n4)remove friend" << endl;
cout << "5)modify food\n6)display friends/food" << endl;
cin >> selection;
if(selection[0] == '1') { //optimized
string name, food;
cout << "what is the persons name followed by favorite food on a new line " << endl;
cin.ignore();
getline(cin, name);
getline(cin, food);
person p = person(name, food);
int p1 = get_person(people, p.name);
if(p1 == -1) {
people.push_back(p);
}
}
else if(selection[0] == '2') { //optimized
display_list_of_friends(people);
}
else if(selection[0] == '3') { //optimized
cout << "which relationship do you want to start (enter two names, seperated by newlines)?" << endl;
string first, second;
cin.ignore();
getline(cin, first);
getline(cin, second);
int p1 = get_person(people, first);
int p2 = get_person(people, second);
if(p1 != -1 and p2 != -1 and first!= second) {
people[p1].add_friend(second);
people[p2].add_friend(first);
}
}
else if(selection[0] == '4') { //optimized
cout << "which relationship do you want to end (enter two names, seperated by newlines)?" << endl;
string first, second;
cin.ignore();
getline(cin, first);
getline(cin, second);
int p1 = get_person(people, first);
int p2 = get_person(people, second);
if (p1 != -1 and p2 != -1) {
people[p1].delete_friend(people[p2].name);
people[p2].delete_friend(people[p1].name);
}
}
else if(selection[0] == '5') { //optimized
string name;
cout << "what is the name of the person to whom you would like to modify fav food?" << endl;
cin.ignore();
getline(cin, name);
int p1 = get_person(people, name);
if(p1 != -1) {
string new_food;
cout << "what food do you want to add?" << endl;
getline(cin, new_food);
people[p1].modify_food(new_food);
}
}
else if(selection[0] == '6') {
cout << "What is the name of the person to whom you would like to view friends with same food?" << endl;
string name;
cin.ignore();
getline(cin, name);
int p1 = get_person(people, name);
if(p1 != -1) {
people[p1].display_person(people);
}
}
else if(selection[0] == 'q') {
break;
}
}
}

47
cs142/lab08/person.cpp Normal file
View File

@ -0,0 +1,47 @@
#include <iostream>
#include <string>
using namespace std;
#include "person.h"
void person::modify_food(string new_food) {
fav_food = new_food;
}
void person::display_person(vector<person> & p) {
for(unsigned int i = 0; i < friends.size(); i++) {
for(unsigned int j = 0; j < p.size(); j++) {
if(p[j].name == friends[i] and p[j].fav_food == fav_food) {
cout << p[j].name << " also likes " << fav_food << endl;
}
}
}
}
void person::add_friend(string name) {
if(not already_friends(name)) {
friends.push_back(name);
}
}
bool person::already_friends(string name) {
for(unsigned int i = 0; i < friends.size(); i++) {
if(friends[i] == name) {
return true;
}
}
return false;
}
void person::delete_friend(string name) {
for(unsigned int i = 0; i < friends.size(); i++) {
if(friends[i] == name) {
friends.erase((friends.begin())+i);
break;
}
else {
cerr << "this person does not exist" << endl;
}
}
}

24
cs142/lab08/person.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef __PERSON_H__
#define __PERSON_H__
#include <iostream>
#include <vector>
using namespace std;
class person {
public:
string name;
string fav_food;
vector<string> friends;
person(string new_name, string food) {
name = new_name;
fav_food = food;
};
void modify_food(string new_food);
void display_person(vector<person> & p);
void add_friend(string name);
bool already_friends(string name);
void delete_friend(string name);
};
#endif

43
cs142/lab08/test.cc Normal file
View File

@ -0,0 +1,43 @@
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ostream & operator<<(ostream & os, vector<string> & v) {
os << "[";
for(auto &i: v) {
os << i << ", ";
}
os << "]";
return os;
}
int main() {
vector<string> people = {
"bilbo",
"frodo",
"samwise",
"gandalf",
"aragorn",
"aowen",
"gollum",
"gimli",
"legalos",
};
cout << people << endl;
vector<string>::iterator it = find(people.begin(), people.end(), "gandalf");
if(it != people.end())
people.erase(it);
cout << people << endl;
it = find(people.begin(), people.end(), "frodo");
if(it != people.end())
people.erase(it);
cout << people << endl;
it = find(people.begin(), people.end(), "Lord Voldemort");
if(it != people.end())
people.erase(it);
cout << people << endl;
}

21
cs142/lab08/test.txt Normal file
View File

@ -0,0 +1,21 @@
2
1
stephen
apples
1
derek
panda
2
3
stephen
derek
2
1
colleen
bananna
2
3
colleen
derek
2
q

29
cs142/lab09/Makefile Normal file
View File

@ -0,0 +1,29 @@
CXXFLAGS=-Wall -g -std=c++0x -Ijsoncpp -DJSON_IS_AMALGAMATION
all: app iotest
app: main.o tournament.o restaurant.o json.o io.o
$(CXX) $(CXXFLAGS) main.o restaurant.o tournament.o io.o json.o -o $@
main.o: main.cpp
restaurant.o: restaurant.cpp restaurant.h
tournament.o: tournament.cpp tournament.h
io.o: io.h io.cpp
json.o: jsoncpp/jsoncpp.cpp
$(CXX) $(CXXFLAGS) $< -c -o $@
iotest: iotest.cpp io.o json.o restaurant.o
clean:
@rm -vf *.o
@rm -vf app
@rm -vf iotest
@rm -rvf *.dSYM
test: all
@./app
io: iotest
@./iotest restaurants.db
debug: all
gdb rest

30
cs142/lab09/io.cpp Normal file
View File

@ -0,0 +1,30 @@
#include <string>
#include <fstream>
#include <streambuf>
#include <stdexcept>
using namespace std;
#include "jsoncpp/json/json.h"
#include "io.h"
#include "restaurant.h"
vector<restaurant> parse_file(string filename) {
vector<restaurant> restaurants;
ifstream infile(filename.c_str());
string file_contents((istreambuf_iterator<char>(infile)),
istreambuf_iterator<char>());
Json::Value root;
Json::Reader reader;
bool good_parse = reader.parse(file_contents, root);
if(not good_parse) {
throw runtime_error(reader.getFormattedErrorMessages());
}
for(unsigned int i = 0; i < root.size(); i++) {
string name = root[i]["name"].asString();
int score = root[i]["score"].asInt();
restaurant r(name, score);
restaurants.push_back(r);
}
return restaurants;
}

11
cs142/lab09/io.h Normal file
View File

@ -0,0 +1,11 @@
#ifndef __IO_H__
#define __IO_H__
#include <vector>
#include <string>
using namespace std;
#include "restaurant.h"
vector<restaurant> parse_file(string filename);
#endif

27
cs142/lab09/iotest.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
#include "io.h"
#include "restaurant.h"
const string usage = "usage: iotest <input json file>";
int main(int argc, char * argv[]) {
if (argc != 2) {
cerr << usage << endl;
return 1;
}
try {
vector<restaurant> v = parse_file(argv[1]);
for(auto r: v) {
cout << r << endl;
}
}
catch(runtime_error e) {
cerr << e.what() << endl;
}
return 0;
}

View File

@ -0,0 +1,249 @@
/// Json-cpp amalgated forward header (http://jsoncpp.sourceforge.net/).
/// It is intented to be used with #include <json/json-forwards.h>
/// This header provides forward declaration for all JsonCpp types.
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
========================================================================
(END LICENSE TEXT)
The MIT license is compatible with both the GPL and commercial
software, affording one all of the rights of Public Domain with the
minor nuisance of being required to keep the above copyright notice
and license text in the source code. Note also that by accepting the
Public Domain "license" you can re-license your copy using whatever
license you like.
*/
// //////////////////////////////////////////////////////////////////////
// End of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
#ifndef JSON_FORWARD_AMALGATED_H_INCLUDED
# define JSON_FORWARD_AMALGATED_H_INCLUDED
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
#define JSON_IS_AMALGATED
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_CONFIG_H_INCLUDED
# define JSON_CONFIG_H_INCLUDED
/// If defined, indicates that json library is embedded in CppTL library.
//# define JSON_IN_CPPTL 1
/// If defined, indicates that json may leverage CppTL library
//# define JSON_USE_CPPTL 1
/// If defined, indicates that cpptl vector based map should be used instead of std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
/// If defined, indicates that Json specific container should be used
/// (hash table & simple deque container with customizable allocator).
/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332
//# define JSON_VALUE_USE_INTERNAL_MAP 1
/// Force usage of standard new/malloc based allocator instead of memory pool based allocator.
/// The memory pools allocator used optimization (initializing Value and ValueInternalLink
/// as if it was a POD) that may cause some validation tool to report errors.
/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined.
//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1
/// If defined, indicates that Json use exception to report invalid type manipulation
/// instead of C assert macro.
# define JSON_USE_EXCEPTION 1
/// If defined, indicates that the source file is amalgated
/// to prevent private header inclusion.
/// Remarks: it is automatically defined in the generated amalgated header.
// #define JSON_IS_AMALGAMATION
# ifdef JSON_IN_CPPTL
# include <cpptl/config.h>
# ifndef JSON_USE_CPPTL
# define JSON_USE_CPPTL 1
# endif
# endif
# ifdef JSON_IN_CPPTL
# define JSON_API CPPTL_API
# elif defined(JSON_DLL_BUILD)
# define JSON_API __declspec(dllexport)
# elif defined(JSON_DLL)
# define JSON_API __declspec(dllimport)
# else
# define JSON_API
# endif
// If JSON_NO_INT64 is defined, then Json only support C++ "int" type for integer
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
#if defined(_MSC_VER) && _MSC_VER <= 1200 // MSVC 6
// Microsoft Visual Studio 6 only support conversion from __int64 to double
// (no conversion from unsigned __int64).
#define JSON_USE_INT64_DOUBLE_CONVERSION 1
#endif // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6
#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
/// Indicates that the following function is deprecated.
# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
#endif
#if !defined(JSONCPP_DEPRECATED)
# define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
namespace Json {
typedef int Int;
typedef unsigned int UInt;
# if defined(JSON_NO_INT64)
typedef int LargestInt;
typedef unsigned int LargestUInt;
# undef JSON_HAS_INT64
# else // if defined(JSON_NO_INT64)
// For Microsoft Visual use specific types as long long is not supported
# if defined(_MSC_VER) // Microsoft Visual Studio
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
# else // if defined(_MSC_VER) // Other platforms, use long long
typedef long long int Int64;
typedef unsigned long long int UInt64;
# endif // if defined(_MSC_VER)
typedef Int64 LargestInt;
typedef UInt64 LargestUInt;
# define JSON_HAS_INT64
# endif // if defined(JSON_NO_INT64)
} // end namespace Json
#endif // JSON_CONFIG_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/config.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_FORWARDS_H_INCLUDED
# define JSON_FORWARDS_H_INCLUDED
#if !defined(JSON_IS_AMALGAMATION)
# include "config.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
// writer.h
class FastWriter;
class StyledWriter;
// reader.h
class Reader;
// features.h
class Features;
// value.h
typedef unsigned int ArrayIndex;
class StaticString;
class Path;
class PathArgument;
class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
#ifdef JSON_VALUE_USE_INTERNAL_MAP
class ValueMapAllocator;
class ValueInternalLink;
class ValueInternalArray;
class ValueInternalMap;
#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
} // namespace Json
#endif // JSON_FORWARDS_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: include/json/forwards.h
// //////////////////////////////////////////////////////////////////////
#endif //ifndef JSON_FORWARD_AMALGATED_H_INCLUDED

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

75
cs142/lab09/main.cpp Normal file
View File

@ -0,0 +1,75 @@
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <vector>
using namespace std;
#include "restaurant.h"
#include "tournament.h"
#include "io.h"
int main() {
tournament t;
bool keep_going = true;
bool file_correct = false;
string input, input_file_name;
const string usage = "usage: iotest <input json file>";
while(!file_correct) {
cout << "please enter file name: ";
getline(cin, input);
ifstream inputs(input.c_str());
if(inputs.good()) {
input_file_name = input;
file_correct = true;
}
else {
cerr << "incorrect file name" << endl;
}
}
t.populate_restaurants(input_file_name);
bool succeful_pop = false;
while(keep_going) {
cout << "1)Display all restaurants\n2)Add a restaurant\n3)Remove a restaurant" << endl;
cout << "4)Shufflle the array\n5)Begin the tournament" << endl;
cin >> input;
if(input[0] == '1'){
cout << t << endl;
}
else if(input[0] == '2'){
t.add_restaurants();
}
else if(input[0] == '3'){
t.remove_restaurants();
}
else if(input[0] == '4'){
t.shuffle();
}
else if(input[0] == '5'){
if(t.verify_size()) {
keep_going = false;
succeful_pop = true;
}
}
else if(input[0] == '0'){
keep_going = false;
}
}
if(succeful_pop) {
t.start_tournament();
string output_file_name;
file_correct = false;
while(!file_correct) {
cout << "please enter file name: ";
getline(cin, output_file_name);
ofstream out(output_file_name.c_str());
if(out.good()) {
out << t;
file_correct = true;
}
else {
cerr << "incorrect file name" << endl;
}
}
}
}

View File

@ -0,0 +1,8 @@
#include "restaurant.h"
using namespace std;
ostream & operator<<(ostream & os, restaurant & r) {
os << "{\"name\": \"" << r.name << "\", \"score\": " << r.score << "}";
return os;
}

16
cs142/lab09/restaurant.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef __RESTAURANT_H__
#define __RESTAURANT_H__
#include <string>
#include <ostream>
using namespace std;
class restaurant {
public:
string name;
int score;
restaurant(string name, int score): name(name), score(score) {}
friend ostream & operator<<(ostream & os, restaurant & r);
};
#endif

5
cs142/lab09/test.json Normal file
View File

@ -0,0 +1,5 @@
[
{"name": "Italian Stallion", "score": 0},
{"name": "Pizza Planet", "score": 20},
{"name": "Gousteau's", "score": 500}
]

196
cs142/lab09/tournament.cpp Normal file
View File

@ -0,0 +1,196 @@
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
using namespace std;
#include "tournament.h"
#include "restaurant.h"
#include "io.h"
ostream & operator<<(ostream & os, vector<restaurant> & v) {
for(auto i: v) {
os << i << endl;
}
return os;
}
ostream & operator<<(ostream & os, tournament & t){
os << "[";
for(unsigned int i = 0; i < t.restaurants.size(); i++) {
if(i == t.restaurants.size() - 1) {
os << t.restaurants[i];
}
else {
os << t.restaurants[i]<< " ,";
}
}
os << "]";
return os;
}
bool tournament::populate_restaurants(string filename) {
try {
restaurants = parse_file(filename);
return true;
}
catch(runtime_error e) {
cerr << e.what() << endl;
return false;
}
}
bool tournament::already_in(string name) {
for(unsigned int i = 0; i < restaurants.size(); i++) {
if(restaurants[i].name == name) {
return true;
}
}
return false;
}
void tournament::add_restaurants() {
string name;
int score = 0;
cout << "name" << endl;
cin.ignore();
getline(cin, name);
if(not already_in(name)) {
restaurants.push_back(restaurant(name, score));
}
}
void tournament::remove_restaurants() {
string name;
cout << "name" << endl;
cin.ignore();
getline(cin, name);
if(already_in(name)) {
for(unsigned int i = 0; i < restaurants.size(); i++) {
if(restaurants[i].name == name){
restaurants.erase(restaurants.begin() + i);
}
}
}
}
void tournament::shuffle() {
random_shuffle(restaurants.begin(), restaurants.end());
}
int round_counter(int current_size) {
int round;
if(current_size == 32) {
round = 5;
}
if(current_size == 16) {
round = 4;
}
else if(current_size == 8) {
round = 3;
}
else if(current_size == 4) {
round = 2;
}
else if(current_size == 2) {
round =1;
}
return round;
}
int match_counter(int current_size) {
int match;
if(current_size == 32) {
match = 16;
}
if(current_size == 16) {
match = 8;
}
else if(current_size == 8) {
match = 4;
}
else if(current_size == 4) {
match = 2;
}
else if(current_size == 2) {
match =1;
}
return match;
}
bool tournament::start_tournament(){
if(not verify_size()) {
cout << "not 2^n" << endl;
return false;
}
bool temp_bool = true;
bool tourn_running = true;
cin.ignore();
string name;
int match = match_counter(restaurants.size());
int round = round_counter(restaurants.size());
int current_round = 1;
vector<restaurant> temp_array;
while(tourn_running == true) {
int current_match = 1;
temp_bool = true;
cin.ignore();
for(unsigned int i = 0; i < restaurants.size(); i += 2) {
while(temp_bool == true) {
cout << "which restaurant: " << restaurants[i] << " or " << restaurants[i + 1] << endl;
cout << "match " << current_match << "/" << match << " Round "
<< current_round << "/" << round << endl;
getline(cin, name);
if(name == restaurants[i].name or name == restaurants[i + 1].name) {
if(name == restaurants[i].name) {
restaurants[i].score++;
temp_array.push_back(restaurants[i]);
losers.push_back(restaurants[i+1]);
}
else {
restaurants[i+1].score++;
temp_array.push_back(restaurants[i + 1]);
losers.push_back(restaurants[i]);
}
temp_bool = false;
current_match++;
}
else {
cout << "invalid response " << name << endl;
}
}
temp_bool = true;
}
while(temp_bool == true) {
for(unsigned int i = 0; i < temp_array.size(); i++) {
restaurants[i] = temp_array[i];
}
for(unsigned int i = 0; i < temp_array.size(); i++){
restaurants.pop_back();
}
if(restaurants.size() == 1) {
losers.push_back(restaurants[0]);
cout << "this is the winner " << restaurants[0] << endl;
restaurants = losers;
return true;
}
else {
cout << "next round of tournament" << endl;
temp_bool = false;
}
}
temp_array.clear();
match = match/2;
current_round++;
}
return false;
}
bool tournament::verify_size() {
int r = restaurants.size();
if(r == 2 or r == 4 or r == 8 or r == 16 or r == 32 or r == 64) {
return true;
}
return false;
}

25
cs142/lab09/tournament.h Normal file
View File

@ -0,0 +1,25 @@
#ifndef __TOURNAMENT_H__
#define __TOURNAMENT_H__
#include <vector>
#include "restaurant.h"
using namespace std;
class tournament {
private:
vector<restaurant> restaurants;
vector<restaurant> losers;
public:
tournament(){};
void display_restaurant();
bool populate_restaurants(string filename);
bool already_in(string name);
void add_restaurants();
void remove_restaurants();
void shuffle();
bool start_tournament();
bool verify_size();
friend ostream & operator<<(ostream & os, tournament & t);
};
#endif

View File

@ -0,0 +1,56 @@
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "FighterInterface.h"
using namespace std;
/*
WARNING: It is expressly forbidden to modify any part of this document, including its name
*/
class ArenaInterface
{
public:
ArenaInterface(){}
virtual ~ArenaInterface(){}
/*
addFighter(string)
Adds a new fighter to the collection of fighters in the arena. Do not allow
duplicate names. Reject any string that does not adhere to the format
outlined in the lab specs.
Return true if a new fighter was added; false otherwise.
*/
virtual bool addFighter(string info) = 0;
/*
removeFighter(string)
Removes the fighter whose name is equal to the given name. Does nothing if
no fighter is found with the given name.
Return true if a fighter is removed; false otherwise.
*/
virtual bool removeFighter(string name) = 0;
/*
getFighter(string)
Returns the memory address of a fighter whose name is equal to the given
name. Returns NULL if no fighter is found with the given name.
Return a memory address if a fighter is found; NULL otherwise.
*/
virtual FighterInterface* getFighter(string name) = 0;
/*
getSize()
Returns the number of fighters in the arena.
Return a non-negative integer.
*/
virtual int getSize() = 0;
};

176
cs142/lab10/Battle.h Normal file
View File

@ -0,0 +1,176 @@
#include <iostream>
#include <string>
#include <sstream>
#include <cstdio>
#include "FighterInterface.h"
using namespace std;
/*
WARNING: It is expressly forbidden to modify any part of this document, including its name
*/
//=======================================================================================
FighterInterface* fight(FighterInterface*, FighterInterface*, bool);
void takeTurn(FighterInterface*, FighterInterface*, bool);
void speak(string);
//=======================================================================================
/*
fight(FighterInterface, FighterInterface, bool)
Runs through the fighting algorithm for the two given fighters.
Each fighter takes a turn using its special ability, attacking, and regenerating. If
the other fighter's current hit points falls to or drops below 0, then the other
fighter has lost. This process repeats until one fighter has fallen or 100 rounds
have occurred with neither fighter falling.
If the given bool is true, this function will print a great deal of information
during the battle. This can be useful for testing.
Returns the winner of the fight; null if the fight ends in a draw.
*/
FighterInterface* fight(FighterInterface* c1, FighterInterface* c2, bool verbose)
{
if(verbose)
{
stringstream stream;
stream << "----------";
stream << c1->getName();
stream << " vs ";
stream << c2->getName();
stream << "----------";
speak(stream.str());
}
c1->reset();
c2->reset();
for(int i=0; i<100; i++)
{
//C1's turn
takeTurn(c1, c2, verbose);
if(c2->getCurrentHP() <= 0)
{
if(verbose)
{
stringstream stream;
stream << c1->getName();
stream << " wins! (";
stream << c1->getCurrentHP();
stream << "/";
stream << c1->getMaximumHP();
stream << " HP left)";
speak(stream.str());
}
return c1;
}
//C2's turn
takeTurn(c2, c1, verbose);
if(c1->getCurrentHP() <= 0)
{
if(verbose)
{
stringstream stream;
stream << c2->getName();
stream << " wins! (";
stream << c2->getCurrentHP();
stream << "/";
stream << c2->getMaximumHP();
stream << " HP left)";
speak(stream.str());
}
return c2;
}
}
if(verbose)
{
speak("After 100 rounds, neither fighter has fallen. It's a draw!");
}
return NULL;
}
//=======================================================================================
/*
takeTurn(FighterInterface*, FighterInterface*, bool)
Runs through a single turn for [attacker] attacking [defender]. Each turn consists of
[attacker] trying to use its special ability, attacking [defender], and regenerating.
*/
void takeTurn(FighterInterface* attacker, FighterInterface* defender, bool verbose)
{
//Header
if(verbose)
{
stringstream stream;
stream << "It's ";
stream << attacker->getName();
stream << "'s turn! (";
stream << attacker->getCurrentHP();
stream << "/";
stream << attacker->getMaximumHP();
stream << " HP).";
speak(stream.str());
}
//Use Ability
if(!attacker->isSimplified())
{
bool ability = attacker->useAbility();
if(ability && verbose)
{
stringstream stream;
stream << "\t";
stream << attacker->getName();
stream << " uses a special ability!";
speak(stream.str());
}
}
//Attack
int damage = attacker->getDamage();
int before_attack = defender->getCurrentHP();
defender->takeDamage(damage);
int after_attack = defender->getCurrentHP();
if(verbose)
{
stringstream stream;
stream << "\t";
stream << attacker->getName();
stream << " attacks with ";
stream << damage;
stream << " damage, and ";
stream << defender->getName();
stream << " takes ";
stream << (before_attack-after_attack);
stream << " damage.";
speak(stream.str());
}
//Regenerate
if(!attacker->isSimplified())
{
int before_regen = attacker->getCurrentHP();
attacker->regenerate();
int after_regen = attacker->getCurrentHP();
if(verbose)
{
stringstream stream;
stream << "\t";
stream << attacker->getName();
stream << " regenerates ";
stream << (after_regen-before_regen);
stream << " HP.";
speak(stream.str());
}
}
}
//=======================================================================================
/*
speak(string)
Displays a given message.
*/
void speak(string message)
{
printf("%s\n", message.c_str());
}
//=======================================================================================

7
cs142/lab10/Factory.cpp Normal file
View File

@ -0,0 +1,7 @@
#include "Factory.h"
#include "arena.h"
ArenaInterface* Factory::createArena()
{
return new arena();
}

21
cs142/lab10/Factory.h Normal file
View File

@ -0,0 +1,21 @@
#pragma once
#include "ArenaInterface.h"
/*
WARNING: It is expressly forbidden to modify any part of this document, including its name
*/
//=======================================================================================
/*
createArena()
Creates and returns an object whose class extends ArenaInterface.
This should be an object of a class you have created.
Example: If you made a class called "Arena", you might say, "return new Arena();".
*/
class Factory
{
public:
static ArenaInterface* createArena();
};
//=======================================================================================

View File

@ -0,0 +1,200 @@
#pragma once
#include <iostream>
#include <string>
using namespace std;
/*
WARNING: It is expressly forbidden to modify any part of this document, including its name
*/
/*
This class specifies the methods for a fighter.
All fighters have the following attributes:
Name - The fighter's name.
Hit Points - The amount of health the fighter has, with a specified maximum. Reaching 0 is equivalent to death.
Strength - Physical power, used to determine hit point regeneration.
Speed - Dexterity and physical movement, used to reduce damage when being attacked.
Magic - Magical prowess, used for some special abilities.
The three fighter types have unique abilities:
Robot - Relies on strength to deal damage. Also can use stored electricity to temporarily increase damage (max electricity equal to 2*magic).
Archer - Relies on speed to deal damage. Also can increase its speed for the remainder of the battle (no max bonus speed).
Cleric - Relies on magic to deal damage. Also can heal itself using mana, restoring hit points (max mana equal to 5*magic).
More details about how stats are used and how abilities work can be found in the comments below.
*/
/*
ROBOT_ABILITY_COST
The amount of energy a Robot needs to perform its special ability.
*/
const int ROBOT_ABILITY_COST = 5;
/*
CLERIC_ABILITY_COST
The amount of mana a Cleric needs to perform its special ability.
*/
const int CLERIC_ABILITY_COST = 25;
class FighterInterface
{
public:
FighterInterface(){}
virtual ~FighterInterface(){}
/*
getName()
Returns the name of this fighter.
*/
virtual string getName() = 0;
/*
getMaximumHP()
Returns the maximum hit points of this fighter.
*/
virtual int getMaximumHP() = 0;
/*
getCurrentHP()
Returns the current hit points of this fighter.
*/
virtual int getCurrentHP() = 0;
/*
getStrength()
Returns the strength stat of this fighter.
*/
virtual int getStrength() = 0;
/*
getSpeed()
Returns the speed stat of this fighter.
*/
virtual int getSpeed() = 0;
/*
getMagic()
Returns the magic stat of this fighter.
*/
virtual int getMagic() = 0;
/*
getDamage()
Returns the amount of damage a fighter will deal.
Robot:
This value is equal to the Robot's strength plus any additional damage added for having just used its special ability.
Archer:
This value is equal to the Archer's speed.
Cleric:
This value is equal to the Cleric's magic.
*/
virtual int getDamage() = 0;
/*
takeDamage(int)
Reduces the fighter's current hit points by an amount equal to the given
damage minus one fourth of the fighter's speed. This method must reduce
the fighter's current hit points by at least one. It is acceptable for
this method to give the fighter negative current hit points.
Examples:
damage=10, speed=7 => damage_taken=9
damage=10, speed=9 => damage_taken=8
damage=10, speed=50 => damage_taken=1
*/
virtual void takeDamage(int damage) = 0;
/*
reset()
Restores a fighter's current hit points to its maximum hit points.
Robot:
Also restores a Robot's current energy to its maximum value (which is 2 times its magic).
Also resets a Robot's bonus damage to 0.
Archer:
Also resets an Archer's current speed to its original value.
Cleric:
Also restores a Cleric's current mana to its maximum value (which is 5 times its magic).
*/
virtual void reset() = 0;
/*
regenerate()
Increases the fighter's current hit points by an amount equal to one sixth of
the fighter's strength. This method must increase the fighter's current hit
points by at least one. Do not allow the current hit points to exceed the
maximum hit points.
Cleric:
Also increases a Cleric's current mana by an amount equal to one fifth of the
Cleric's magic. This method must increase the Cleric's current mana by at
least one. Do not allow the current mana to exceed the maximum mana.
*/
virtual void regenerate() = 0;
/*
useAbility()
Attempts to perform a special ability based on the type of fighter. The
fighter will attempt to use this special ability just prior to attacking
every turn.
Robot: Shockwave Punch
Adds bonus damage to the Robot's next attack (and only its next attack) equal to (strength * ((current_energy/maximum_energy)^4)).
Can only be used if the Robot has at least [ROBOT_ABILITY_COST] energy.
Decreases the Robot's current energy by [ROBOT_ABILITY_COST] (after calculating the additional damage) when used.
Examples:
strength=20, current_energy=20, maximum_energy=20 => bonus_damage=20
strength=20, current_energy=15, maximum_energy=20 => bonus_damage=6
strength=20, current_energy=10, maximum_energy=20 => bonus_damage=1
strength=20, current_energy=5, maximum_energy=20 => bonus_damage=0
Robot Note:
The bonus damage formula should be computed using double arithmetic, and only
the final result should be cast into an integer.
Archer: Quickstep
Increases the Archer's speed by one point each time the ability is used.
This bonus lasts until the reset() method is used.
This ability always works; there is no maximum bonus speed.
Cleric: Healing Light
Increases the Cleric's current hit points by an amount equal to one third of its magic.
Can only be used if the Cleric has at least [CLERIC_ABILITY_COST] mana.
Will be used even if the Cleric's current HP is equal to their maximum HP
Decreases the Cleric's current mana by [CLERIC_ABILITY_COST] when used.
Cleric Note:
This ability, when successful, must increase the Cleric's current hit points
by at least one. Do not allow the current hit points to exceed the maximum
hit points.
Return true if the ability was used; false otherwise.
*/
virtual bool useAbility() = 0;
/*
isSimplified()
Returns true if you have not completed the useAbility() and/or the regenerate()
methods for this type of fighter. This allows the test driver to award points
for Part 3 even if Part 4 is incomplete.
Return true if the testing is to be simplified; false otherwise.
*/
virtual bool isSimplified() = 0;
};

33
cs142/lab10/Makefile Normal file
View File

@ -0,0 +1,33 @@
CXXFLAGS= -Wall -g
OBJECTS=main.o arena.o Factory.o archer.o fighter.o util.o cleric.o robot.o
EXE=main
all: $(EXE)
$(EXE): main.o
$(CXX) $(CXXFLAGS) $(OBJECTS) -o $@
main.o: main.cpp Factory.o arena.o fighter.o archer.o util.o cleric.o robot.o
Factory.o: Factory.cpp Factory.h
arena.o: arena.cpp arena.h
fighter.o: fighter.cpp fighter.h
archer.o: archer.cpp archer.h fighter.h
cleric.o: cleric.cpp cleric.h fighter.h
robot.o: robot.cpp robot.h fighter.h
util.o: util.cpp util.h
run: $(EXE)
@./$(EXE)
clean:
@rm -vf *.o
@rm -vf $(EXE)
debug: $(EXE)
gdb ./$(EXE)
valgrind: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE)

21
cs142/lab10/archer.cpp Normal file
View File

@ -0,0 +1,21 @@
#include "archer.h"
archer::archer(string name, int max_hp, int strength, int speed, int magic) :
fighter(name, max_hp, strength, speed, magic), original_speed(speed) {}
int archer::getDamage() {
return speed;
}
void archer::reset() {
hp = max_hp;
speed = original_speed;
}
bool archer::useAbility() {
speed++;
return true;
}
int archer::get_original_speed() {
return original_speed;
}

21
cs142/lab10/archer.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef __ARCHER_H__
#define __ARCHER_H__
#include "fighter.h"
class archer : public fighter {
private:
int original_speed;
public:
archer(string, int, int, int, int);
string get_type() { return "A"; };
int getDamage();
void reset();
bool useAbility();
int get_original_speed();
};
#endif

111
cs142/lab10/arena.cpp Normal file
View File

@ -0,0 +1,111 @@
#include <vector>
using namespace std;
#include "arena.h"
#include "fighter.h"
#include "archer.h"
#include "cleric.h"
#include "robot.h"
#include "util.h"
arena::~arena() {
fighter * f = NULL;
for(vector<FighterInterface *>::iterator it = fighters.begin();
it != fighters.end();
it++) {
f = dynamic_cast<fighter *>(*it);
delete f;
}
}
bool arena::contains(string name) {
fighter * f = NULL;
for(unsigned int i = 0; i < fighters.size(); i++) {
f = dynamic_cast<fighter *>(fighters[i]);
if(f->getName() == name) {
return true;
}
}
return false;
}
bool arena::addFighter(string info) {
fighter * f = NULL;
string name;
string type;
int max_hp;
int strength;
int speed;
int magic;
bool worked;
worked = parse_n_load(info, name, type, max_hp, strength, speed, magic);
if(not worked) {
return false;
}
if(contains(name)) {
return false;
}
if(type == "A") {
f = new archer(name, max_hp, strength, speed, magic);
}
else if(type == "C") {
f = new cleric(name, max_hp, strength, speed, magic);
}
else if(type == "R") {
f = new robot(name, max_hp, strength, speed, magic);
}
fighters.push_back(f);
return true;
}
bool arena::removeFighter(string name) {
fighter * f = NULL;
for(vector<FighterInterface *>::iterator it = fighters.begin();
it != fighters.end();
it++) {
f = dynamic_cast<fighter *>(*it);
if(f->getName() == name) {
delete f;
fighters.erase(it);
return true;
}
}
return false;
}
FighterInterface * arena::getFighter(string name) {
fighter * f = NULL;
for(vector<FighterInterface *>::iterator it = fighters.begin();
it != fighters.end();
it++) {
f = dynamic_cast<fighter *>(*it);
if(f->getName() == name) {
return dynamic_cast<FighterInterface *>(f);
}
}
return NULL;
}
int arena::getSize() {
return fighters.size();
}
ostream & operator<<(ostream & os, arena & a) {
os << "[";
for(vector<FighterInterface * >::iterator it = a.fighters.begin();
it != a.fighters.end();
it++) {
os << *(dynamic_cast<fighter *>( *it));
if (it != a.fighters.end() - 1) {
os << ", ";
}
}
os << "]";
return os;
}

23
cs142/lab10/arena.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef __ARENA_H__
#define __ARENA_H__
#include <vector>
#include "ArenaInterface.h"
class arena : public ArenaInterface {
private:
std::vector<FighterInterface *> fighters;
bool contains(string name);
public:
arena(){}
~arena();
bool addFighter(string info);
bool removeFighter(string name);
FighterInterface * getFighter(string name);
int getSize();
friend ostream & operator<<(ostream &, arena &);
};
#endif

59
cs142/lab10/cleric.cpp Normal file
View File

@ -0,0 +1,59 @@
#include "FighterInterface.h"
#include "cleric.h"
cleric::cleric(string name, int max_hp, int strength, int speed, int magic) :
fighter(name, max_hp, strength, speed, magic), mana(5*magic) {}
int cleric::getDamage() {
return magic;
}
void cleric::reset() {
hp = max_hp;
mana = 5 * magic;
}
void cleric::regenerate() {
fighter::regenerate();
int increase = magic / 5;
if(increase < 0) {
increase = 0;
}
else if(increase == 0) {
increase = 1;
}
if(mana + increase < magic * 5) {
mana += increase;
}
else {
mana = 5 * magic;
}
}
bool cleric::useAbility() {
// a.k.a. Healing light
if(mana - CLERIC_ABILITY_COST >= 0) {
int increase = magic / 3;
if(increase < 0) {
increase = 0;
}
else if(increase == 0) {
increase = 1;
}
if(hp + increase < max_hp) {
hp += increase;
}
else {
hp = max_hp;
}
mana -= CLERIC_ABILITY_COST;
return true;
}
return false;
}
int cleric::get_mana() {
return mana;
}

24
cs142/lab10/cleric.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef __CLERIC_H__
#define __CLERIC_H__
#include "fighter.h"
class cleric : public fighter {
private:
int original_speed;
int mana;
public:
cleric(string, int, int, int, int);
string get_type() { return "A"; };
int getDamage();
void reset();
bool useAbility();
void regenerate();
int get_original_speed();
int get_mana();
};
#endif

72
cs142/lab10/fighter.cpp Normal file
View File

@ -0,0 +1,72 @@
#include "fighter.h"
fighter::fighter(string name, int max_hp, int strength, int speed, int magic) :
name(name), max_hp(max_hp), hp(max_hp), strength(strength),
speed(speed), magic(magic) {}
string fighter::getName() {
return name;
}
int fighter::getMaximumHP() {
return max_hp;
}
int fighter::getCurrentHP() {
return hp;
}
int fighter::getStrength() {
return strength;
}
int fighter::getSpeed() {
return speed;
}
int fighter::getMagic() {
return magic;
}
void fighter::regenerate() {
int increase = strength / 6;
if(increase < 0) {
increase = 0;
}
else if(increase == 0) {
increase = 1;
}
if(hp + increase <= max_hp) {
hp += increase;
}
else {
hp = max_hp;
}
}
void fighter::takeDamage(int damage) {
int hurt = damage - (speed / 4);
if (hurt <= 0) {
hurt = 1;
}
hp -= hurt;
}
bool fighter::isSimplified() {
return false;
}
ostream & operator<<(ostream & os, fighter & f) {
os << "{\n"
<< " \"name\": \"" << f.name << "\",\n"
<< " \"type\": \"" << f.get_type() << "\",\n"
<< " \"hp\": " << f.hp << ",\n"
<< " \"max hp\": " << f.max_hp << ",\n"
<< " \"strength\": " << f.strength << ",\n"
<< " \"speed\": " << f.speed << ",\n"
<< " \"magic\": " << f.magic << ",\n"
<< "}";
return os;
}

44
cs142/lab10/fighter.h Normal file
View File

@ -0,0 +1,44 @@
#ifndef __FIGHTER_H__
#define __FIGHTER_H__
#include <ostream>
#include "FighterInterface.h"
class fighter : public FighterInterface
{
private:
string name;
protected:
int max_hp;
int hp;
int strength;
int speed;
int magic;
public:
fighter(string, int, int, int, int);
// virtual ~fighter();
string getName();
int getMaximumHP();
int getCurrentHP();
int getStrength();
int getSpeed();
int getMagic();
virtual string get_type() = 0;
virtual int getDamage() = 0;
void takeDamage(int damage);
virtual void reset() = 0;
virtual void regenerate();
virtual bool useAbility() = 0;
bool isSimplified();
friend ostream & operator<<(ostream & os, fighter & a);
};
#endif

205
cs142/lab10/main.cpp Normal file
View File

@ -0,0 +1,205 @@
#include <iostream>
#include <cassert>
using namespace std;
#include "Battle.h"
#include "Factory.h"
#include "arena.h"
#include "archer.h"
#include "cleric.h"
#include "robot.h"
void test_fighter() {
archer a = archer("bilbo", 100, 60, 1, 5);
a.takeDamage(90);
a.regenerate();
assert(a.getCurrentHP() == 20);
archer b = archer("frodo", 100, 0, 1, 5);
b.takeDamage(90);
b.regenerate();
}
void test_archer() {
archer a("stephen", 666, 66, 6, 0);
a.takeDamage(100);
assert(a.getCurrentHP() == 567);
assert(a.get_original_speed() == 6);
assert(a.getSpeed() == 6);
}
void test_cleric() {
cleric a("Derek", 666, 66, 6, 20);
assert(a.getDamage() == 20);
assert(a.get_mana() == 100);
a.takeDamage(100);
assert(a.getCurrentHP() == 567);
a.reset();
assert(a.getCurrentHP() == 666);
cleric b("SaintColleen", 100, 90, 4, 60);
b.takeDamage(100);
b.useAbility();
assert(b.getCurrentHP() == 21);
cleric c("Vanessa", 100, 90, 4, 1);
c.takeDamage(100);
c.useAbility();
assert(c.getCurrentHP() == 1);
cleric d("Vanessa", 100, 90, 4, 5);
d.takeDamage(100);
d.useAbility();
assert(d.getCurrentHP() == 2);
}
void test_robot() {
robot a("Derek", 100, 20, 10, 10);
assert(a.getDamage() == 20);
a.useAbility();
assert(a.getDamage() == 40);
assert(a.getDamage() == 20);
a.useAbility();
assert(a.getDamage() == 26);
a.takeDamage(100);
assert(a.getCurrentHP() == 2);
a.reset();
assert(a.getCurrentHP() == 100);
}
void test_input_parser() {
ArenaInterface * A = Factory::createArena();
arena * a = dynamic_cast<arena *>(A);
string input = "Xephos A 200 13 21 10";
assert(a->addFighter(input));
input = "Stephen A 200 13 21 10";
assert(a->addFighter(input));
input = "Billy Bob Thorton A 0 13 21 10";
assert(not a->addFighter(input));
input = "Xephos a 200 13 21 10";
assert(not a->addFighter(input));
input = "Derek A 200 13 21 a10";
assert(not a->addFighter(input));
input = "Derek A 200 13 stupid21 10";
assert(not a->addFighter(input));
delete A;
}
void test_add() {
ArenaInterface * A = Factory::createArena();
arena * a = dynamic_cast<arena *>(A);
string input = "Xephos A 200 13 21 10";
assert(a->addFighter(input));
input = "Stephen A 200 13 21 10";
assert(a->addFighter(input));
// do not allow for duplicate fighers
input = "Xephos A 200 13 21 10";
bool double_add = a->addFighter(input);
assert(not double_add);
input = "Stephen A 0 13 21 10";
assert(not a->addFighter(input));
input = "Derek A 200 13 21 10";
assert(a->addFighter(input));
// another attempt for not allowing duplicate fighters
input = "Stephen A 200 13 21 10";
assert(not a->addFighter(input));
delete A;
}
void test_remove() {
ArenaInterface * A = Factory::createArena();
arena * a = dynamic_cast<arena *>(A);
string input = "Michael A 200 13 21 10";
a->addFighter(input);
input = "Derek A 200 13 21 10";
a->addFighter(input);
input = "Bryan A 200 13 21 10";
a->addFighter(input);
assert(not a->removeFighter("Zaphodbeblebrox"));
bool remove_non_existant = a->removeFighter("Stephen");
assert(not remove_non_existant);
assert(a->getSize() == 3);
bool remove_fighter = a->removeFighter("Michael");
assert(remove_fighter);
assert(a->getSize() == 2);
a->removeFighter("Derek");
a->removeFighter("Bryan");
assert(a->getSize() == 0);
delete a;
}
void test_find() {
ArenaInterface * A = Factory::createArena();
arena * a = dynamic_cast<arena *>(A);
string input = "Michael A 200 13 21 10";
a->addFighter(input);
input = "Derek A 200 13 21 10";
a->addFighter(input);
input = "Bryan A 200 13 21 10";
a->addFighter(input);
fighter * f;
f = dynamic_cast<fighter *>(a->getFighter("Stephen"));
assert(not f);
f = dynamic_cast<fighter *>(a->getFighter("Derek"));
assert(f);
delete a;
}
void test_archer_reset() {
archer a("stephen", 666, 66, 6, 0);
a.takeDamage(100);
assert(a.getCurrentHP() == 567);
a.reset();
assert(a.getCurrentHP() == a.getMaximumHP());
assert(a.getSpeed() == a.get_original_speed());
assert(a.getSpeed() == 6);
assert(a.get_original_speed() == 6);
}
void test_archer_usability() {
archer a("stephen", 666, 66, 6, 0);
assert(a.getSpeed() == 6);
a.useAbility();
assert(a.getSpeed() == 7);
}
void test_battle() {
archer a("stephen", 200, 66, 60, 100);
robot b("derek", 1000, 20, 15, 200);
fight(&a, &b, true);
}
int main() {
test_fighter();
test_archer();
test_cleric();
test_robot();
test_input_parser();
test_add();
test_remove();
test_find();
test_archer_reset();
test_archer_usability();
test_battle();
}

30
cs142/lab10/robot.cpp Normal file
View File

@ -0,0 +1,30 @@
#include <cmath>
#include "FighterInterface.h"
#include "robot.h"
robot::robot(string name, int max_hp, int strength, int speed, int magic) :
fighter(name, max_hp, strength, speed, magic),
max_energy(2 * magic), cur_energy(2 * magic), extra_damage(0) {}
int robot::getDamage() {
int damage = strength + extra_damage;
extra_damage = 0;
return damage;
}
void robot::reset() {
hp = max_hp;
cur_energy = max_energy;
}
bool robot::useAbility() {
if(cur_energy - ROBOT_ABILITY_COST >= 0) {
double a = cur_energy/double(max_energy);
double b = pow(a, 4.0);
double increase = strength * b;
extra_damage = int(increase);
cur_energy -= ROBOT_ABILITY_COST;
return true;
}
return false;
}

23
cs142/lab10/robot.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef __ROBOT_H__
#define __ROBOT_H__
#include "fighter.h"
class robot : public fighter {
private:
int max_energy;
int cur_energy;
int extra_damage;
public:
robot(string, int, int, int, int);
string get_type() { return "A"; };
int getDamage();
void reset();
bool useAbility();
int get_original_speed();
};
#endif

60
cs142/lab10/util.cpp Normal file
View File

@ -0,0 +1,60 @@
#include <vector>
#include <string>
using namespace std;
#include <cstdlib>
#include "util.h"
vector<string> tokenize(const string & str, const string & delimiters) {
vector<string> tokens;
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
bool parse_n_load(const string & input, string & name, string & type,
int & max_hp, int & strength, int & speed, int & magic) {
vector<string> tokens = tokenize(input);
vector<string> tokens2 = tokenize(input, ".");
if (tokens.size() != 6 or tokens2.size() > 1) {
return false;
}
name = tokens[0];
string parsed_type = tokens[1];
if(parsed_type.size() != 1) {
return false;
}
if (not ( parsed_type == "A"
or parsed_type == "C"
or parsed_type == "R")) {
return false;
}
type = parsed_type;
int parsed_max_hp = atoi(tokens[2].c_str());
int parsed_strength = atoi(tokens[3].c_str());
int parsed_speed = atoi(tokens[4].c_str());
int parsed_magic = atoi(tokens[5].c_str());
if (parsed_max_hp == 0 or parsed_strength == 0 or parsed_speed == 0 or
parsed_magic == 0) {
return false;
}
max_hp = parsed_max_hp;
strength = parsed_strength;
speed = parsed_speed;
magic = parsed_magic;
return true;
}

14
cs142/lab10/util.h Normal file
View File

@ -0,0 +1,14 @@
#ifndef __UTIL_H__
#define __UTIL_H__
#include <string>
#include <vector>
using namespace std;
void print(const string & in);
vector<string> tokenize(const string & str, const string & delimiters=" ");
bool parse_n_load(const string & input, string & name, string & type,
int & max_hp, int & strength, int & speed, int & magic);
#endif

View File

@ -0,0 +1,14 @@
CPPFLAGS=-Wall -g -std=c++0x
all: cootie
cootie: cootie.cc dice.o player.o
dice.o: dice.cc dice.h
player.o: player.cc player.h
test: all
./cootie 4
clean:
@rm -rvf cootie cootie.dSYM *.o

View File

@ -0,0 +1,42 @@
#include <iostream>
#include <vector>
#include <cstdlib>
#include "dice.h"
#include "player.h"
using namespace std;
const string usage = "usage: cootie <number of players>";
int main(int argc, char * argv[]) {
if(argc < 2) {
cerr << usage << endl;;
return 1;
}
random_init();
int number_of_players = int(atof(argv[1]));
vector<player> players;
for(int i=0; i < number_of_players; i++) {
players.push_back(player(i));
}
auto keep_playing = true;
while(keep_playing) {
for(player & p : players) {
// cout << p << endl;
p.turn();
if(p.won()) {
keep_playing = false;
cout << "player " << p.id << " wins!!" << endl;
cout << p << endl;
break;
}
}
}
cout << "total rolls: " << get_roll_count() << endl;
cout << "thanks for playing" << endl;
return 0;
}

View File

@ -0,0 +1,25 @@
#include <cstdlib>
#include <ctime>
#include <sys/time.h>
#include <unistd.h>
#include "dice.h"
static int roll_count = 0;
void random_init() {
struct timeval tv;
gettimeofday(&tv, NULL);
pid_t pid = getpid();
srand(tv.tv_usec + pid);
}
int roll() {
roll_count++;
int compliment = rand() % 6;
return compliment + 1;
}
int get_roll_count() {
return roll_count;
}

View File

@ -0,0 +1,8 @@
#ifndef __DICE_H__
#define __DICE_H__
void random_init();
int roll();
int get_roll_count();
#endif

View File

@ -0,0 +1,67 @@
#include "dice.h"
#include "player.h"
#include <iostream>
using namespace std;
player::player(int id) : id(id), head(false), body(false),
hat(false), eyes(false), mouth(false), legs(0) {}
ostream & operator<<(ostream & os, const player & e) {
os << "{id: " << e.id
<< ", body: " << e.body
<< ", head: " << e.head
<< ", hat: " << e.hat
<< ", eyes: " << e.eyes
<< ", mouth: " << e.mouth
<< ", legs: " << e.legs
<< "}";
return os;
}
void player::turn() {
bool turn_finished = false;
while(not turn_finished) {
int cur_roll = roll();
turn_finished = true;
if(cur_roll == 1) {
if(not body) {
turn_finished = false;
body = true;
}
}
else if(body and cur_roll == 2) {
if(not head) {
turn_finished = false;
head = true;
}
}
else if(body and head) {
if (cur_roll == 3) {
turn_finished = false;
hat = true;
}
else if (cur_roll == 4) {
turn_finished = false;
eyes = true;
}
else if (cur_roll == 5) {
turn_finished = false;
mouth = true;
}
else if (cur_roll == 6) {
if (not (legs >= 6)) {
turn_finished = false;
legs++;
}
}
}
}
}
bool player::won() {
if(head and body and hat and eyes and mouth and legs == 6)
return true;
else
return false;
}

View File

@ -0,0 +1,24 @@
#ifndef __PLAYER_H__
#define __PLAYER_H__
#include <ostream>
using namespace std;
class player {
public:
int id;
bool head;
bool body;
bool hat;
bool eyes;
bool mouth;
int legs;
player(int);
friend ostream & operator<<(ostream &, const player &);
void turn();
bool won();
};
#endif

View File

@ -0,0 +1,9 @@
CPPFLAGS=-Wall -g -std=c++0x
all: main
test: all
./main
clean:
@rm -rfv main.o main

View File

@ -0,0 +1,34 @@
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
using namespace std;
int main(int argc, char * argv[]) {
float a = 12.123456;
float b = 12.125100;
cout << a << " " << b << " " << endl;
cout << setiosflags(ios::fixed) << setprecision(2) << a << " " << b << " " << endl;
printf("%0.2f %0.2f\n", a, b);
fprintf(stdout, "%0.2f %0.2f\n", a, b);
fprintf(stderr, "%0.2f %0.2f\n", a, b);
double input;
cin >> input;
double intpart = 0;
double fracpart = modf(input, &intpart);
printf("%f %f\n", intpart, fracpart);
if (fracpart == 0.5) {
cout << "exactly 0.5" << endl;
}
else {
cout << "not exactly 0.5" << endl;
}
return 0;
}

View File

@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=hello
GOFILES=\
hello.go
include $(GOROOT)/src/Make.cmd

View File

@ -0,0 +1,7 @@
package main
import "fmt"
func main() {
fmt.Println("hello world! My name is Stephen McQuay.")
}

View File

@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=trivia
GOFILES=\
trivia.go
include $(GOROOT)/src/Make.cmd

View File

@ -0,0 +1,29 @@
package main
import "fmt"
type QA struct {
question string
answer string
}
func main() {
fmt.Printf("%48s\n", "Basic BYU Trivia")
fmt.Printf("%25s %38s\n\n", "Questions", "Answers")
qas := []QA{
{"What was the original name of BYU?", "Brigham Young Academy"},
{"When was BYU established?", "1875"},
{"Who was the first \"permanent\" principal of BYA?",
"Karl G. Maeser"},
{"When did BYA become BYU?", "1903"},
{"To what sports conference do we belong?",
"Mountain West Conference (MWC)"},
{"WHen did BYU win the national football title?", "1984"},
{"Who won the Heisman Trophy in 1990?", "Ty Detmer"},
}
for _, v := range qas {
fmt.Printf("%-48s %s\n", v.question, v.answer)
}
}

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