adding cs142 code

This commit is contained in:
dm
2016-04-06 20:45:34 -07:00
parent 552d456d53
commit 8e52ce1982
174 changed files with 14064 additions and 0 deletions
+14
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
+42
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;
}
+25
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;
}
+8
View File
@@ -0,0 +1,8 @@
#ifndef __DICE_H__
#define __DICE_H__
void random_init();
int roll();
int get_roll_count();
#endif
+67
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;
}
+24
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
@@ -0,0 +1,9 @@
CPPFLAGS=-Wall -g -std=c++0x
all: main
test: all
./main
clean:
@rm -rfv main.o main
+34
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;
}
+7
View File
@@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=hello
GOFILES=\
hello.go
include $(GOROOT)/src/Make.cmd
+7
View File
@@ -0,0 +1,7 @@
package main
import "fmt"
func main() {
fmt.Println("hello world! My name is Stephen McQuay.")
}
+7
View File
@@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=trivia
GOFILES=\
trivia.go
include $(GOROOT)/src/Make.cmd
+29
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)
}
}
+7
View File
@@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=binary
GOFILES=\
binary.go
include $(GOROOT)/src/Make.cmd
+26
View File
@@ -0,0 +1,26 @@
package main
import (
"fmt"
)
func itob(i int) string {
var buf [64]byte
j := len(buf)
b := 2
for i > 0 {
j--
buf[j] = "0123456789abcdefghipqrstuvwxyz"[i%b]
i /= b
}
return string(buf[j:])
}
func main() {
var i int
fmt.Print("please enter a number: ")
fmt.Scan(&i)
fmt.Printf("%d as a binary: %s\n", i, itob(i))
}
+7
View File
@@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=seconds
GOFILES=\
seconds.go
include $(GOROOT)/src/Make.cmd
+36
View File
@@ -0,0 +1,36 @@
package main
import (
"fmt"
"math"
)
const SECONDS_PER_HOUR = 3600
const SECONDS_PER_MINUTE = 60
type time struct {
hours int
minutes int
seconds int
}
func (t time) String() string {
return fmt.Sprintf("%dH:%dM:%dS", t.hours, t.minutes, t.seconds);
}
func int2time(i int) time {
var r_secs int
hours := i / SECONDS_PER_HOUR
r_secs = i % SECONDS_PER_HOUR
mins := r_secs / SECONDS_PER_MINUTE
r_secs = r_secs % SECONDS_PER_MINUTE
return time{hours, mins, r_secs}
}
func main() {
var seconds int
fmt.Print("please enter total seconds: ")
fmt.Scan(&seconds)
fmt.Printf("%v\n", int2time(seconds))
fmt.Printf("%v\n", int2time(int(math.Sqrt(float64(seconds)))))
}
@@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=temp
GOFILES=\
temp.go
include $(GOROOT)/src/Make.cmd
@@ -0,0 +1,21 @@
package main
import (
"fmt"
)
func f2c(temp_F float32) float32 {
return 5.0/9.0 * (temp_F-32);
}
func main() {
var temp_F float32
fmt.Print("please enter a temperature: ")
fmt.Scan(&temp_F)
temp_C := f2c(temp_F)
fmt.Printf("%0.4fF as:\n", temp_F)
fmt.Printf("an int: %dF\n", int(temp_F))
fmt.Printf("a celsius float32: %0.4fC\n", temp_C)
fmt.Printf("a celcius int: %dC\n", int(temp_C))
}
+7
View File
@@ -0,0 +1,7 @@
include $(GOROOT)/src/Make.inc
TARG=grades
GOFILES=\
grades.go
include $(GOROOT)/src/Make.cmd
+10
View File
@@ -0,0 +1,10 @@
package main
import (
"fmt"
)
func main() {
fmt.Println("hello")
}
+10
View File
@@ -0,0 +1,10 @@
CXXFLAGS=-Wall -g -std=c++0x
all: grade
test: grade
./grade < test.txt
./grade -n < test.txt
./grade -p < test.txt
clean:
@rm -vf grade
@rm -rvf grade.dSYM
+211
View File
@@ -0,0 +1,211 @@
#include <iostream>
#include <sstream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int MIN_SCORE = 0;
const string usage = "\
usage: grade [-n, --by-name] [-p, --by-points] [-v, --verbose]";
struct student {
string name;
int lab_score;
int exam_score;
int final_score;
string letter_grade;
};
typedef struct student student;
ostream & operator<<(ostream & os, const student & s) {
os << "name: '" << s.name
<< ", final score: " << s.final_score
<< ", grade: " << s.letter_grade;
return os;
}
bool sort_by_name(const student & a, const student & b) {
return a.name < b.name;
}
bool sort_by_score(const student & a, const student & b) {
return a.final_score > b.final_score;
}
struct grade {
int max_score;
int min_late_days;
int max_late_days;
};
typedef struct grade grade;
struct result {
int score;
int late_days;
};
typedef struct result result;
result collect_grade(string name, int score_max,
int late_min, int late_max, bool verbose);
string determine_letter_grade(int score);
int main(int argc, char * argv[]) {
bool verbose = false;
bool by_points = false;
bool by_name = false;
for(int i = 0; i < argc; i++) {
string cur_arg = argv[i];
if(cur_arg == "--verbose" or cur_arg == "-v") {
verbose = true;
}
if(cur_arg == "--by-points" or cur_arg == "-p") {
by_points = true;
}
if(cur_arg == "--by-name" or cur_arg == "-n") {
by_name = true;
}
if(cur_arg == "--help" or cur_arg == "-h") {
cout << usage << endl;
return 0;
}
}
if (by_points and by_name) {
cerr << "only specify one sort order" << endl;
return -1;
}
map<string, grade> labs = {
{"Lab01", {20, -2, 2}},
{"Lab02", {20, -2, 2}},
{"Lab03", {30, -3, 3}},
{"Lab04", {30, -3, 3}},
{"Lab05", {30, -3, 3}},
{"Lab06", {30, -3, 3}},
{"Lab07", {30, -3, 3}},
{"Lab08", {30, -3, 3}},
{"Lab09", {20, -2, 2}},
{"Lab10", {20, -2, 2}},
{"Lab11", {40, -4, 4}},
{"exam1", {100, 0, 3}},
{"exam2", {100, 0, 3}},
{"final", {100, 0, 3}},
};
vector<student> students;
while (!cin.eof()) {
if(verbose)
cerr << "Please enter name of student: ";
string name;
getline(cin, name);
if (!name.empty()) {
int total_lab_points = 0;
int total_exam_points = 0;
for(pair<string, grade> l: labs) {
string n = l.first;
grade g = l.second;
try {
result cur_result = collect_grade(n, g.max_score,
g.min_late_days, g.max_late_days, verbose);
total_lab_points += cur_result.score;
if (n.substr(0, 3) == "lab")
total_lab_points -= 5 * cur_result.late_days;
else if (n.substr(0, 4) == "exam" or n.substr(0, 4) == "final")
total_exam_points -= 20 * cur_result.late_days;
} catch (string e) {
cerr << e << endl;
return 1;
}
}
int final_score = total_lab_points + total_exam_points;
student s = {name, total_lab_points, total_exam_points,
final_score, determine_letter_grade(final_score)};
students.push_back(s);
}
}
if(by_name) {
sort(students.begin(), students.end(), sort_by_name);
}
else if (by_points) {
sort(students.begin(), students.end(), sort_by_score);
}
for(student s: students) {
cout << s << endl;
}
return 0;
}
result collect_grade(string name, int score_max,
int late_min, int late_max, bool verbose=false) {
int score = 0;
if(verbose) {
cerr << "Please enter score for " << name
<< "[" << MIN_SCORE << ", " << score_max << "]: ";
}
cin >> score;
if (!(MIN_SCORE <= score and score <= score_max)) {
ostringstream s;
s << score << " is not in accepted range: ["
<< MIN_SCORE << ", "
<< score_max << "]" << endl;
throw s.str();
}
int late_days;
if (verbose) {
cerr << "Please enter late days ["
<< late_min << ", " << late_max << "]: ";
}
cin >> late_days;
if (!(late_min <= late_days and late_days <= late_max)) {
ostringstream s;
s << late_days << " is not in accepted range: ["
<< late_min << ", "
<< late_max << "]" << endl;
throw s.str();
}
result r = {score, late_days};
return r;
}
string determine_letter_grade(int score) {
string letter_grade;
if(score >= 570)
letter_grade = "A";
if(score < 570 && score >=540)
letter_grade = "A-";
if(score < 540 && score >= 522)
letter_grade = "B+";
if(score < 522 && score >= 498)
letter_grade = "B";
if(score < 498 && score >= 480)
letter_grade = "B-";
if(score < 480 && score >= 462)
letter_grade = "C+";
if(score < 462 && score >= 438)
letter_grade = "C";
if(score < 438 && score >= 420)
letter_grade = "C-";
if(score < 420 && score >= 402)
letter_grade = "D+";
if(score < 402 && score >= 378)
letter_grade = "D";
if(score < 378 && score >= 360)
letter_grade = "D-";
if(score < 360)
letter_grade = "E";
return letter_grade;
}
+165
View File
@@ -0,0 +1,165 @@
Stephen M. McQuay
10 0
20 0
25 0
15 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
10 0
81 0
100 0
Vanessa H. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
0 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Mardson H. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Penelope R. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Stott Q. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Michael M. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Alicia D. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Max Menahem McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Bryan M. McQuay
20 0
20 0
30 0
30 0
30 0
30 0
30 0
30 0
20 0
20 0
40 0
100 0
100 0
100 0
Derek M. McQuay
20 -2
20 -2
30 -3
30 -3
30 -3
30 -3
30 -3
30 -3
20 -2
20 -2
40 -2
100 0
100 0
99 1
Colleen P. McQuay
20 -2
20 -2
30 -3
30 -3
30 -3
30 -3
30 -3
30 -3
20 -2
20 -2
40 -4
100 0
100 0
100 0
+16
View File
@@ -0,0 +1,16 @@
CPPFLAGS=-Wall -g -std=c++0x
all: magic test00 test01
magic: magic.cc num_set.o converts.o
test00: test00.cc num_set.o converts.o
test01: test01.cc num_set.o converts.o
num_set.o: num_set.cc num_set.h
converts.o: converts.cc converts.h
clean:
@rm -rfv test00 test00.dSYM
@rm -rfv test01 test01.dSYM
@rm -rvf magic magic.dSYM *.o
+17
View File
@@ -0,0 +1,17 @@
#include <iostream>
#include <cmath>
#include "converts.h"
int str2int(string s) {
int r = 0;
int i = 0;
for(auto s_it = s.rbegin(); s_it != s.rend(); s_it++) {
if (*s_it == '1') {
r += pow(2, i);
}
i++;
}
return r;
}
+10
View File
@@ -0,0 +1,10 @@
#ifndef __CONVERTS_H__
#define __CONVERTS_H__
#include <string>
using namespace std;
int str2int(string i);
#endif
+45
View File
@@ -0,0 +1,45 @@
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include "num_set.h"
using namespace std;
const string usage = "usage: magic ";
int main(int argc, char * argv[]) {
string play_again;
srand(time(NULL));
while (true) {
string cur_guess_str;
for(int i=0; i < 5; i++) {
int compliment = rand() % 2;
vector<string> nums = generate_numbers(i, compliment);
cout << nums << endl << endl;
string cur_guess;
cout << "is your number in there: ";
cin >> cur_guess;
if(cur_guess[0] == 'y' or cur_guess[0] == 'Y') {
if(compliment == 0)
cur_guess_str.push_back('0');
else
cur_guess_str.push_back('1');
} else {
if(compliment == 0)
cur_guess_str.push_back('1');
else
cur_guess_str.push_back('0');
}
}
reverse(cur_guess_str.begin(), cur_guess_str.end());
cout << cur_guess_str << ", " << str2int(cur_guess_str) << endl;
cout << "play again? ";
cin >> play_again;
if(!(play_again[0] == 'y' or play_again[0] == 'Y'))
break;
}
cout << "good bye" << endl;
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
#include <iostream>
#include <sstream>
#include <iomanip>
#include "num_set.h"
vector<string> zerone = {"0", "1"};
vector<string> generate_numbers(int constant_index, int compliment) {
vector<string> r;
stringstream out;
out << compliment;
auto compliment_str = out.str();
for(int i=0; i <= 1; i++) {
for(int j=0; j <= 1; j++) {
for(int k=0; k <= 1; k++) {
for(int l=0; l <= 1; l++) {
ostringstream cur_str;
cur_str << i << j << k << l;
string s = cur_str.str();
s.insert(s.size() - constant_index, compliment_str);
r.push_back(s);
}
}
}
}
return r;
}
ostream & operator<<(ostream & os, const vector<string> & nums) {
for (unsigned int i = 0; i < nums.size(); i++) {
os << setw(4) << str2int(nums[i]);
if(i % 4 == 3 and i != nums.size() - 1) {
os << endl;
}
}
return os;
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef __NUM_SET_H__
#define __NUM_SET_H__
#include <vector>
#include <string>
#include <ostream>
#include "converts.h"
using namespace std;
vector<string> generate_numbers(int, int);
ostream & operator<<(ostream &, const vector<string> &);
#endif
+29
View File
@@ -0,0 +1,29 @@
#include <iostream>
#include <sstream>
#include <vector>
#include "num_set.h"
using namespace std;
const string usage = "usage: test <index> <0/1>";
int main(int argc, char * argv[]) {
if (argc < 3) {
cerr << usage << endl;
return 1;
}
int index, compliment;
istringstream iss0(argv[1]);
iss0 >> index;
index = index % 5;
istringstream iss1(argv[2]);
iss1 >> compliment;
compliment = compliment % 2;
vector<string> nums = generate_numbers(index, compliment);
for(string i: nums)
cout << i << endl;
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
#include <iostream>
#include <vector>
#include "num_set.h"
#include "converts.h"
using namespace std;
const string usage = "usage: test <index> <0/1>";
int main() {
vector<string> nums = generate_numbers(0, 0);
cout << "should print evens:" << endl;
for(string n: nums) {
int i = str2int(n);
cout << ">>> " << n << ", " << i << endl;
}
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
SOURCES=restaurant.cc sm_array.cc collect.cc tournament.cc
OBJECTS=$(SOURCES:.cc=.o)
EXE=restaurant
all: $(EXE)
$(EXE): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
sm_array.o: sm_array.cc sm_array.h
collect.o: collect.cc collect.h sm_array.h
tournament.o: tournament.cc tournament.h
test-display: test-display.cc sm_array.o collect.o test_constants.h
test-contains: test-contains.cc sm_array.o collect.o test_constants.h
test-remove: test-remove.cc sm_array.o collect.o test_constants.h
test-add: test-add.cc sm_array.o collect.o test_constants.h
test-random: test-random.cc sm_array.o collect.o test_constants.h
clean:
@rm -vf *.o
@rm -rvf *.dSYM
@rm -vf restaurant
@rm -vf test-display
@rm -vf test-random
@rm -vf test-contains
@rm -vf test-remove
@rm -vf test-add
test: test-random test-display test-contains test-remove test-add
./test-display
./test-contains
./test-remove
./test-add
@echo "remember to manually inspect test-random"
run: restaurant
./restaurant
+75
View File
@@ -0,0 +1,75 @@
#include <iostream>
#include "collect.h"
ostream & operator<<(ostream & os, const vector<string> & s) {
os << "menu:\n";
for(auto i: s) {
os << " " << i << endl;
}
return os;
}
garray initial_restaurants() {
garray a;
a.add("Cafe Rio");
a.add("Pappa Murphy's");
a.add("Quiznos");
a.add("Jimmy Johns");
a.add("Thai Chili Gardens");
a.add("Subway");
a.add("Taco Bell");
a.add("India Palace");
return a;
}
garray populate_restaurants() {
string input;
bool running = true;
garray restaurants = initial_restaurants();
while(running) {
cout << "\n" << menu << endl;
cout << "your selection: ";
cin >> input;
cout << endl;
if(input[0] == 'd') {
cout << restaurants << endl;
}
else if(input[0] == 'a') {
cout << "which restaurant should I ADD: ";
string name;
cin.ignore();
getline(cin, name);
bool add_results = restaurants.add(name);
if(add_results) {
cout << "added '" << name << "' successfully!" << endl;
}
else {
cerr << "did not add: '" << name << "' "
<< "(already there or max size)" << endl;
}
}
else if(input[0] == 'r') {
cout << "which restaurant should I REMOVE: ";
string name;
cin.ignore();
getline(cin, name);
bool remove_results = restaurants.remove(name);
if(remove_results) {
cout << "removed '" << name << "' successfully!" << endl;
}
else {
cerr << "did not remove: '" << name << "' "
<< "(probably not in array)" << endl;
}
}
else if(input[0] == 's') {
restaurants.randomize();
}
else if(input[0] == 'b') {
running = false;
}
}
return restaurants;
}
+25
View File
@@ -0,0 +1,25 @@
#ifndef __COLLECT_H__
#define __COLLECT_H__
#include <vector>
#include <string>
#include <ostream>
using namespace std;
#include "sm_array.h"
const vector<string> menu = {
"(d)isplay",
"(a)dd",
"(r)emove",
"(s)huffle",
"(b)egin",
};
ostream & operator<<(ostream &, const vector<string> &);
garray initial_restaurants();
garray populate_restaurants();
#endif
+20
View File
@@ -0,0 +1,20 @@
#include <iostream>
using namespace std;
#include "sm_array.h"
#include "collect.h"
#include "tournament.h"
int main(int argc, char * argv[]) {
garray restaurants = populate_restaurants();
string restaurant_to_rule_them_all;
try {
restaurant_to_rule_them_all = tournament(restaurants);
}
catch (string e) {
cerr << e << endl;
}
cout << ">>> winner: " << restaurant_to_rule_them_all << endl;
return 0;
}
+65
View File
@@ -0,0 +1,65 @@
#include <algorithm>
#include "sm_array.h"
garray::garray(): size(0) {};
bool garray::add(string name) {
if(name == "") {
throw string("cannot add empty string");
}
if((not contains(name)) and size < MAX_DATA_SIZE) {
data[size] = name;
size++;
return true;
}
else {
return false;
}
}
bool garray::contains(string name) {
for(int i = 0; i < size; i++) {
if(name == data[i])
return true;
}
return false;
}
bool garray::remove(string name) {
bool reduce = false;
if(contains(name)) {
reduce = true;
}
else {
return reduce;
}
garray tmp;
for(int i = 0; i < size; i++) {
if(data[i] != name) {
tmp.add(data[i]);
}
}
for(int i = 0; i < MAX_DATA_SIZE; i++) {
data[i] = tmp.data[i];
}
if(reduce)
size--;
return reduce;
}
void garray::randomize() {
random_shuffle(&data[0], &data[size]);
}
ostream & operator<<(ostream & os, garray & g) {
os << "[";
for(int i = 0; i < g.size; i++) {
os << i << "-" << g.data[i];
if (i != g.size - 1) {
os << ", ";
}
}
os << "]";
return os;
}
+28
View File
@@ -0,0 +1,28 @@
#ifndef __SM_ARRAY_H__
#define __SM_ARRAY_H__
#include <ostream>
#include <string>
using namespace std;
const int MAX_DATA_SIZE = 16;
struct garray {
// gimpy string container that cannot be larger than 16,
// and cannot contain empty strings
int size;
string data [MAX_DATA_SIZE];
garray();
bool add(string name);
bool remove(string name);
void randomize();
bool contains(string name);
};
ostream & operator<<(ostream &, garray &);
#endif
+43
View File
@@ -0,0 +1,43 @@
#include <iostream>
#include <string>
using namespace std;
#include "sm_array.h"
#include "collect.h"
#include "test_constants.h"
int main(int argc, char * argv[]) {
garray a;
bool raised_error = false;
bool correct_error_string = false;
try {
a.add("");
}
catch (string e) {
raised_error = true;
if(e == "cannot add empty string") {
correct_error_string = true;
}
}
if(not raised_error) {
cerr << "should have raised an error trying to add an empty string" << endl;
return 1;
}
if(not correct_error_string) {
cerr << "incorrect error string" << endl;
return 1;
}
garray g = initial_restaurants();
if(g.add("Cafe Rio") or g.add("Jimmy Johns") or not g.add("Jimbo White")) {
cerr << "shouldn't be able to add something that's already in there" << endl;
return 1;
}
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
#include <iostream>
#include <string>
using namespace std;
#include "sm_array.h"
#include "collect.h"
#include "test_constants.h"
int main(int argc, char * argv[]) {
garray a = initial_restaurants();
if(a.contains("Shifty Pete's Tacos")) {
cerr << "should not contain \"Shifty Pete's Tacos\"" << endl;
return 1;
}
if(not a.contains("Taco Bell")) {
cerr << "Should have Taco Bell" << endl;
return 1;
}
if(not a.contains("Cafe Rio")) {
cerr << "Failed test at beginning" << endl;
return 1;
}
if(not a.contains("India Palace")) {
cerr << "Failed test at end" << endl;
return 1;
}
if(a.contains("")) {
cerr << "should not contain empty string" << endl;
return 1;
}
return 0;
}
+29
View File
@@ -0,0 +1,29 @@
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#include "sm_array.h"
#include "collect.h"
#include "test_constants.h"
int main(int argc, char * argv[]) {
garray a = initial_restaurants();
ostringstream output;
output << a;
if(output.str() != TEST_ARRAY_OUTPUT) {
cerr << "problem with text output" << endl;
return 1;
}
if(a.size != TEST_ARRAY_SIZE) {
cerr << "problem with expected test array size" << endl;
return 1;
}
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
#include "sm_array.h"
#include "collect.h"
#include "test_constants.h"
int main(int argc, char * argv[]) {
srand(time(NULL));
garray a = initial_restaurants();
cout << " >>> " << a << endl;
cout << "should print the previous array in random orders: " << endl;
for(int i = 0; i < 10; i++) {
a.randomize();
cout << " >>> " << a << endl;
}
return 0;
}
+89
View File
@@ -0,0 +1,89 @@
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#include "sm_array.h"
#include "collect.h"
#include "test_constants.h"
int main(int argc, char * argv[]) {
ostringstream output;
garray a = initial_restaurants();
string expected;
bool successful_removal;
int expected_size;
successful_removal = a.remove("");
output << a;
expected = TEST_ARRAY_OUTPUT;
expected_size = 8;
if(output.str() != expected
and a.size != expected_size
and successful_removal) {
cerr << "improper removal of empty string" << endl;
cerr << "have: " << a << ", " << a.size << endl;
cerr << "expected: " << expected << ", " << expected_size << endl;
return 1;
}
successful_removal = a.remove("Taco Bell");
output << a;
expected = "[Cafe Rio, Pappa Murphy's, Quiznos, Jimmy Johns, Thai Chili Gardens, Subway, India Palace]";
expected_size = 7;
if(output.str() != expected
and a.size != expected_size
and not successful_removal) {
cerr << "improper removal from middle (Taco Bell)" << endl;
cerr << "have: " << a << ", " << a.size << endl;
cerr << "expected: " << expected << ", " << expected_size << endl;
return 1;
}
successful_removal = a.remove("India Palace");
output.str("");
output << a;
expected = "[Cafe Rio, Pappa Murphy's, Quiznos, Jimmy Johns, Thai Chili Gardens, Subway]";
expected_size = 6;
if(output.str() != expected
and a.size != expected_size
and not successful_removal) {
cerr << "improper removal from end (India palace)" << endl;
cerr << "have: " << a << ", " << a.size << endl;
cerr << "expected: " << expected << ", " << expected_size << endl;
return 1;
}
successful_removal = a.remove("Shitar's Palace");
output.str("");
output << a;
// same expected as last time
expected_size = 6;
if(output.str() != expected
and a.size != expected_size
and successful_removal) {
cerr << "improper removal of value that is not in the list" << endl;
cerr << "have: " << a << ", " << a.size << endl;
cerr << "expected: " << expected << ", " << expected_size << endl;
return 1;
}
successful_removal = a.remove("Cafe Rio");
output.str("");
output << a;
expected = "[Pappa Murphy's, Quiznos, Jimmy Johns, Thai Chili Gardens, Subway]";
expected_size = 6;
if(output.str() != expected
and a.size != expected_size
and not successful_removal) {
cerr << "improper removal from beginning (Cafe Rio)" << endl;
cerr << "have: " << a << ", " << a.size << endl;
cerr << "expected: " << expected << ", " << expected_size << endl;
return 1;
}
return 0;
}
+12
View File
@@ -0,0 +1,12 @@
#ifndef __TESTFUNCS_H__
#define __TESTFUNCS_H__
#include <string>
const std::string TEST_ARRAY_OUTPUT =
"[0-Cafe Rio, 1-Pappa Murphy's, 2-Quiznos, "
"3-Jimmy Johns, 4-Thai Chili Gardens, 5-Subway, 6-Taco Bell, 7-India Palace]";
const int TEST_ARRAY_SIZE = 8;
#endif
+46
View File
@@ -0,0 +1,46 @@
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
#include "tournament.h"
int is_pow_2 (unsigned int x) {
return ((x != 0) && ((x & (~x + 1)) == x));
}
string tournament(garray & restaurants) {
if(not is_pow_2(restaurants.size)){
ostringstream o;
o << restaurants.size << " is not a power of 2";
throw o.str();
}
string selection;
bool finished = false;
while(not finished) {
garray tmp;
for(int i=0; i < restaurants.size / 2; i++) {
int a_i = 2*i;
int b_i = a_i + 1;
string a = restaurants.data[a_i];
string b = restaurants.data[b_i];
cout << "(a) " << a << " (b) " << b << endl;
cout << "your selection: ";
cin >> selection;
if(selection[0] == 'a')
tmp.add(a);
else
tmp.add(b);
}
if(tmp.size == 1) {
finished = true;
selection = tmp.data[0];
}
else {
restaurants = tmp;
}
}
return selection;
}
+11
View File
@@ -0,0 +1,11 @@
#ifndef __TOURNAMENT_H__
#define __TOURNAMENT_H__
#include <string>
using namespace std;
#include "sm_array.h"
string tournament(garray &);
#endif
+32
View File
@@ -0,0 +1,32 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
SOURCES=cookies.cc main.cc
OBJECTS=$(SOURCES:.cc=.o)
EXE=app
all: $(EXE)
main.o: cookies.cc cookies.h
cookies.o: cookies.cc cookies.h
$(EXE): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
clean:
@rm -vf *.o
@rm -rvf *.dSYM
@rm -vf app
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
+92
View File
@@ -0,0 +1,92 @@
#include<string>
#include <iostream>
#include "cookies.h"
void addOrder(string * cookies[], int * size, string new_name) {
string * s = findOrder(cookies, size, new_name);
if(s == NULL)
s = new string(new_name);
cookies[*size] = s;
(*size)++;
}
int deliverOrder(string * cookies[], int * size, string name) {
string * s = findOrder(cookies, size, name);
if(s == NULL)
return 0;
// interesting note, temp_cookies gets allocatied on the stack and (see
// note above return) ...
string * temp_cookies [MAXIMUM_SIZE] = {};
int removes = 0;
int temp_pos = 0;
for(int i = 0; i < *size; i++) {
if(cookies[i] == s) {
// pass
removes += 1;
}
else {
temp_cookies[temp_pos] = cookies[i];
temp_pos++;
}
}
// copy from the tmp buffer into the original passed-by-pointer array
for(int i = 0; i < temp_pos; i++) {
cookies[i] = temp_cookies[i];
}
*size = temp_pos;
// this removes the memory newed above (in addOrder) from the HEAP
delete s;
// ... temp_cookies (along with removes and temp_pos) gets cleaned up at
// this point ... Stack stack stack
return removes;
}
bool modifyOrder(string * cookies[], int * size, string original_name, string new_name) {
string * s = findOrder(cookies, size, original_name);
if(s == NULL)
return false;
*s = new_name;
return true;
}
string displayOrders(string * cookies[], int * size) {
string r;
for(int i=0; i < *size; i++) {
r += *cookies[i];
if(i < *size - 1)
r += ", ";
}
return r;
}
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;
}
void clean_up(string * cookies[], int * size) {
string * deletable_cookies [MAXIMUM_SIZE] = {};
int del_size = 0;
for(int i = 0; i < *size; i++) {
if(!findOrder(deletable_cookies, &del_size, *cookies[i])) {
deletable_cookies[del_size] = cookies[i];
del_size++;
}
}
for(int i = 0; i < del_size; i++)
delete deletable_cookies[i];
}
+73
View File
@@ -0,0 +1,73 @@
#ifndef __COOKIES_H__
#define __COOKIES_H__
#include <string>
using namespace std;
const int MAXIMUM_SIZE = 10;
/*
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);
/*
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);
/*
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);
/*
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);
/*
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);
void clean_up(string * cookies[], int * size);
#endif
+130
View File
@@ -0,0 +1,130 @@
#include <iostream>
#include <string>
using namespace std;
#include "cookies.h"
int getOption(int range);
string getName(string message);
int main()
{
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 of the order:");
string new_name = getName("Please enter the new customer's name for the order:");
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;
}
clean_up(cookies, size);
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
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;
}
+17
View File
@@ -0,0 +1,17 @@
1
stephen
1
michael
1
michael
1
stephen
1
derek
3
stephen
Stephen Mardson McQuay
2
michael
2
derek
+37
View File
@@ -0,0 +1,37 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
SOURCES=main.cc menu.cc person.cc people.cc
OBJECTS=$(SOURCES:.cc=.o)
EXE=app
all: $(EXE)
main.o: main.cc person.o people.o menu.o
menu.o: menu.h menu.cc
person.o: person.cc person.h
people.o: people.cc people.h
$(EXE): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
clean:
@rm -vf *.o
@rm -rvf *.dSYM
@rm -vf app
run: $(EXE)
./$(EXE)
test: $(EXE)
./$(EXE) < test.txt
debug: $(EXE)
gdb $(EXE)
valgrind: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE)
autov: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE) < test.txt
+102
View File
@@ -0,0 +1,102 @@
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "menu.h"
#include "person.h"
#include "people.h"
int main() {
people peeps;
peeps.add_person("Kevin Bacon", "bacon");
menu m;
string option;
bool done = false;
while(not done) {
cout << endl << m;
getline(cin, option);
if(option[0] == '#')
continue;
if (option[0] == 'a') {
cout << "adding a person" << endl;
string name, food;
cout << "name: ";
getline(cin, name);
cout << "food: ";
getline(cin, food);
peeps.add_person(name, food);
}
else if (option[0] == 'd') {
cout << "displaying people" << endl;
cout << peeps << endl;
}
else if (option[0] == 'm') {
cout << "make connection" << endl;
cout << peeps << endl;
try {
unsigned int a, b;
get_two_indices(peeps, a, b);
peeps.connect(a, b);
}
catch(string e) {
cerr << e << endl;
}
}
else if (option[0] == 'b') {
cout << "break connection" << endl;
cout << peeps << endl;
try {
unsigned int a, b;
get_two_indices(peeps, a, b);
peeps.unfriend(a, b);
}
catch(string e) {
cerr << e << endl;
}
}
else if (option[0] == 'c') {
cout << "change food" << endl;
cout << peeps << endl;
try {
unsigned int a;
get_index(peeps, a, "enter index of person who needs changing: ");
cout << "new food: ";
cin.ignore();
getline(cin, option);
peeps.food_update(a, option);
}
catch(string e) {
cerr << e << endl;
}
}
else if (option[0] == 's') {
cout << "show food friends" << endl;
try {
unsigned int a;
get_index(peeps, a, "enter index of person for food friend: ");
peeps[a]->food_friend();
}
catch(string e) {
cerr << e << endl;
}
}
else if (option[0] == 'e') {
try {
unsigned int a;
get_index(peeps, a, "enter index of person for who I shall calculate the Bacon Number: ");
cout << peeps[a]->bacon_number() << endl;
}
catch(string e) {
cerr << e << endl;
}
}
else if (option[0] == 'q') {
cout << "quitting" << endl;
done = true;
}
}
return 0;
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
using namespace std;
#include "menu.h"
void get_index(people & p, unsigned int & a, string msg="") {
cout << msg;
cin >> a;
if(a >= p.size()) {
throw string("Not in range!!");
}
}
void get_two_indices(people & p, unsigned int & a, unsigned int & b) {
if(p.size() < 2) {
throw string("Not enough people to perform this operation.");
}
get_index(p, a, "enter first index: ");
get_index(p, b, "enter second index: ");
if(a == b) {
throw string("indices need to be different");
}
}
ostream & operator<<(ostream & os, const menu & m) {
for(auto i: menu_items) {
os << " " << i << endl;
}
os << "your selection: ";
return os;
}
+30
View File
@@ -0,0 +1,30 @@
#ifndef __MENU_H__
#define __MENU_H__
#include <string>
#include <vector>
#include <ostream>
using namespace std;
#include "people.h"
const vector<string> menu_items = {
"(a)dd person",
"(d)isplay",
"(m)ake connection",
"(b)reak connection",
"(c)hange food",
"(s)how food friends",
"(e)xtra credit (bacon number)",
"",
"(q)uit",
};
class menu {};
void get_index(people &, unsigned int &, string);
void get_two_indices(people &, unsigned int &, unsigned int &);
ostream & operator<<(ostream & os, const menu & m);
#endif
+65
View File
@@ -0,0 +1,65 @@
#include "people.h"
people::~people() {
for(auto i: persons) {
delete i;
}
}
bool people::contains(string name) {
for(auto i: persons) {
if(i->name == name) {
return true;
}
}
return false;
}
void people::add_person(string name, string food) {
if(not contains(name)) {
person * tmp = new person(name, food);
persons.push_back(tmp);
}
}
void people::connect(unsigned int a, unsigned int b) {
cout << *this << endl;
person * p1 = persons[a];
person * p2 = persons[b];
p1->friends.insert(p2);
p2->friends.insert(p1);
}
void people::unfriend(unsigned int a, unsigned int b) {
cout << *this << endl;
person * p1 = persons[a];
person * p2 = persons[b];
auto p2it = p1->friends.find(p2);
if(p2it != p1->friends.end())
p1->friends.erase(p2it);
auto p1it = p2->friends.find(p1);
if(p1it != p2->friends.end())
p2->friends.erase(p1it);
}
void people::food_update(unsigned int a, string new_food) {
persons[a]->update_food(new_food);
}
unsigned int people::size() {
return persons.size();
}
person * people::operator[](unsigned int i) {
return persons[i];
}
ostream & operator<<(ostream & os, people & p) {
os << "people (" << p.persons.size() << "):" << endl;
for(unsigned int i=0; i < p.persons.size(); i++) {
os << i << " : " << *p.persons[i] << endl;
}
return os;
}
+29
View File
@@ -0,0 +1,29 @@
#ifndef __PEOPLE_H__
#define __PEOPLE_H__
#include <vector>
#include <string>
#include <iostream>
using namespace std;
#include "person.h"
class people {
vector<person *> persons;
public:
~people();
unsigned int size();
bool contains(string);
void add_person(string, string);
void food_update(unsigned int, string);
void connect(unsigned int, unsigned int);
void unfriend(unsigned int, unsigned int);
person * operator[](unsigned int);
friend ostream & operator<<(ostream &, people &);
};
#endif
+53
View File
@@ -0,0 +1,53 @@
using namespace std;
#include "person.h"
void person::update_food(string new_food) {
if(name != "Kevin Bacon")
favorite_food = new_food;
}
void person::food_friend() {
cout << "freinds for " << this->name << " with similar tastes: [";
for(auto i = friends.begin(); i != friends.end(); i++) {
if((*i)->favorite_food == this->favorite_food) {
cout << "'" << (*i)->name << "', ";
}
}
cout << "]" << endl;
}
int person::bacon_number() {
return 0;
}
ostream &operator<<(ostream &stream, person & p) {
stream << "{name: '" << p.name
<< "', favorite_food: '" << p.favorite_food
<< "'";
if(p.friends.size() > 0) {
stream << ", friends: [";
for(auto i = p.friends.begin(); i != p.friends.end(); i++) {
if (i != p.friends.begin()) {
stream << ", ";
}
stream << "'" << (*i)->name << "'";
}
stream << "]";
}
stream << "}";
return stream;
}
istream &operator>>(istream &stream, person &o) {
string buffer;
cout << "name: ";
stream.ignore();
getline(stream, buffer);
o.name = buffer;
cout << "food: ";
getline(stream, buffer);
o.favorite_food = buffer;
return stream;
}
+25
View File
@@ -0,0 +1,25 @@
#ifndef __PERSON_H__
#define __PERSON_H__
#include <iostream>
#include <string>
#include <set>
using namespace std;
class person {
private:
friend class people;
string name;
string favorite_food;
set<person *> friends;
public:
person(string name, string food): name(name), favorite_food(food) {};
void update_food(string);
void food_friend();
int bacon_number();
friend ostream & operator<<(ostream &, person &);
friend istream & operator>>(istream &, person &);
};
#endif
+138
View File
@@ -0,0 +1,138 @@
# stephen is 1
a
stephen mcquay
panda steaks
# vanessa is 2
a
vanessa mcquay
pringles
# stephen <-> vanessa
m
1
2
# no-op
m
1
2
# derek is 3
a
derek mcquay
panda steaks
# colleen is 4
a
colleen
panda steaks
# out of range
m
12
# derek <-> colleen
m
3
4
# stephen <-> derek
m
1
3
# stephen <-> colleen
m
1
4
d
# no-op
b
0
1
# stephen <-> Kevin Bacon
m
0
1
d
# not allowed:
c
0
Bacon Bits
# Stephen's food is now Bacon Bits
c
1
Bacon Bits
d
# michael is 5
a
Michael
sushi
# bilbo is 6
a
Bilbo Baggins
Bacon Bits
# frodo is 7
a
Frodo Baggins
Bacon Bits
d
# stephen <-> michael
m
1
5
# stephen <-> bilbo
m
1
6
# stephen <-> frodo
m
1
7
d
# show stephen has a few friends who love bacon bits
s
1
c
1
bacon
# show Kevin Bacon's friends
s
0
# remove friendship: stephen <-> bilbo
b
0
6
# show kevin bacon's friends
s
0
# bacon number for stephen:
e
1
d
q
+29
View File
@@ -0,0 +1,29 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
SOURCES=main.cc util.cc person.cc
OBJECTS=$(SOURCES:.cc=.o)
EXE=restaurant
all: $(EXE)
main.o: main.cc util.o person.o
util.o: util.h util.cc
person.o: person.cc person.h
$(EXE): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
run: $(EXE)
./$(EXE) people.db /tmp/output.db
cat /tmp/output.db
clean:
@rm -vf *.o
@rm -rvf *.dSYM
@rm -vf $(EXE)
debug: $(EXE)
gdb $(EXE)
valgrind: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE) people.db /tmp/output.db
+29
View File
@@ -0,0 +1,29 @@
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
using namespace std;
#include "person.h"
#include "util.h"
const string usage = "usage: app <input file> <output file>";
int main(int argc, char * argv []) {
if(argc != 3) {
cerr << usage << endl;
return 1;
}
string input_filename(argv[1]);
string output_filename(argv[2]);
try {
vector<person> people = parse_file(input_filename);
save_file(output_filename, people);
}
catch(runtime_error e) {
cerr << e.what() << endl;
return 1;
}
return 0;
}
+3
View File
@@ -0,0 +1,3 @@
stephen mcquay , 31
derek mcquay , 21
jimmy joshn shimmershi ne the fourth , 32
+7
View File
@@ -0,0 +1,7 @@
#include <ostream>
#include "person.h"
ostream & operator<<(ostream & os, person & p) {
os << p.name << ", " << p.age;
return os;
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef __PERSON_H__
#define __PERSON_H__
#include <ostream>
#include <string>
using namespace std;
struct person {
string name;
int age;
person(string name, int age): name(name), age(age) {};
friend ostream & operator<<(ostream & os, person & p);
};
#endif
+82
View File
@@ -0,0 +1,82 @@
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <stdexcept>
using namespace std;
#include "util.h"
#include "person.h"
ostream & operator<<(ostream & os, vector<int> & v) {
os << "[";
for(unsigned int i = 0; i < v.size(); i++) {
os << v[i];
if(i != v.size() - 1) {
os << ", ";
}
}
os << "]";
return os;
}
vector<string> tokenize(const string & str, const string & delimiters) {
vector<string> tokens;
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
vector<person> parse_file(string filename) {
ifstream inputs(filename.c_str());
if(inputs.good()) {
vector<person> people;
string line;
int age;
while(getline(inputs, line)) {
vector<string> tokens = tokenize(line, ",");
string name = tokens[0];
string age_s = tokens[1];
//clean up name
vector<string> name_tokens = tokenize(name, " ");
name.clear();
for(unsigned int i = 0; i < name_tokens.size(); i++) {
name += name_tokens[i];
if(i != name_tokens.size() - 1) {
name += " ";
}
}
// parse an int
stringstream age_parser(age_s);
age_parser >> age;
people.push_back(person(name, age));
}
return people;
}
else {
throw runtime_error("Input file was not good; please verify.");
}
}
void save_file(string filename, const vector<person> & people) {
ofstream output_file(filename.c_str());
for(auto p: people) {
output_file << p << endl;
}
}
+17
View File
@@ -0,0 +1,17 @@
#ifndef __UTIL_H__
#define __UTIL_H__
#include <vector>
#include <string>
#include <ostream>
using namespace std;
#include "person.h"
ostream & operator<<(ostream &, vector<bool> &);
vector<string> tokenize(const string & str, const string & delimiters=" ");
vector<person> parse_file(string filename);
void save_file(string filename, const vector<person> & people);
#endif
+29
View File
@@ -0,0 +1,29 @@
CXX=g++
CPPFLAGS=-Wall -g -std=c++0x
SOURCES=main.cc util.cc
OBJECTS=$(SOURCES:.cc=.o)
EXE=app
all: $(EXE) test
main.o: main.cc util.o
util.o: util.h util.cc
unittest: util.o unittest.cc
$(EXE): $(OBJECTS)
$(CXX) $(LDFLAGS) $(OBJECTS) -o $@
clean:
@rm -vf *.o
@rm -rvf *.dSYM
@rm -vf $(EXE)
@rm -vf unittest
test: unittest
./unittest
debug: $(EXE)
gdb $(EXE)
valgrind: $(EXE)
valgrind --tool=memcheck --leak-check=yes ./$(EXE)
+22
View File
@@ -0,0 +1,22 @@
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
#include "util.h"
const string usage = "usage: app <number of people> <step>";
int main(int argc, char * argv []) {
if(argc != 3) {
cerr << usage << endl;
return 1;
}
int number_of_people = atoi(argv[1]);
int step = atoi(argv[2]);
vector<bool> people(number_of_people, true);
vector<int> loosers = _play_game(people, step);
cout << loosers[loosers.size()-1] << endl;
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
#include <string>
#include <cassert>
using namespace std;
#include "util.h"
int main(int argc, char * argv []) {
bool verbose = false;
if(argc > 1)
verbose = true;
assert(9 == _test_run(10, 1, verbose));
assert(3 == _test_run(10, 3, verbose));
assert(9 == _test_run(10, 12, verbose));
assert(19 == _test_run(20, 3, verbose));
assert(4 == _test_run(15, 7, verbose));
for(int i=0; i >= -1; i--) {
try {
_test_run(1500000, i);
}
catch(string e) {
assert(e == "rule violation: m > 0");
}
}
return 0;
}
+56
View File
@@ -0,0 +1,56 @@
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "util.h"
ostream & operator<<(ostream & os, vector<int> & v) {
os << "[";
for(unsigned int i = 0; i < v.size(); i++) {
os << v[i];
if(i != v.size() - 1) {
os << ", ";
}
}
os << "]";
return os;
}
int _increment_to_next_looser(const vector<bool> & players,
int start, const int step) {
int counter = 0;
// the test examples in the pdf have us start by killing the m-1th person
// offset by one for some dumb reason
int attempt = start - 1;
while(counter != step) {
attempt = (attempt + 1) % players.size();
if(players[attempt]) {
counter++;
}
}
return attempt;
}
vector<int> _play_game(vector<bool> & players, int step) {
vector<int> loosers;
int token = 0;
while(loosers.size() < players.size()) {
token = _increment_to_next_looser(players, token, step);
players[token] = false;
loosers.push_back(token);
}
return loosers;
}
int _test_run(int n, int m, bool verbose) {
if(m < 1) {
throw string("rule violation: m > 0");
}
vector<bool> players(n, true);
vector<int> loosers = _play_game(players, m);
if(verbose) {
cout << loosers << endl;
}
return loosers[loosers.size()-1];
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef __UTIL_H__
#define __UTIL_H__
#include <vector>
#include <iostream>
using namespace std;
ostream & operator<<(ostream &, vector<bool> &);
vector<int> _play_game(vector<bool> & players, const int step);
int _increment_to_next_looser(const vector<bool> & players, int start, const int step);
int _test_run(int n, int m, bool verbose=false);
#endif
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
CPPFLAGS=-Wall -g -std=c++0x
all: person-test person.o
person-test: person-test.cc person.o
person.o: person.cc person.h
clean:
@rm -fv person-test *.o
+17
View File
@@ -0,0 +1,17 @@
#include <iostream>
using std::cout;
using std::endl;
#include "person.h"
int main(int argc, char * argv[])
{
person p;
p.populate_data();
cout << p << endl;
cout << p.as_string() << endl;
person p2("derek mcquay", 21);
cout << p2 << endl;
}
+25
View File
@@ -0,0 +1,25 @@
#include "person.h"
void person::populate_data() {
cout << "enter name: ";
getline(cin, name);
cout << "enter age: ";
cin >> age;
}
string person::as_string() const {
ostringstream stm;
stm << "name: "
<< name
<< ", age: "
<< age;
return stm.str();
}
ostream & operator<<(ostream & os, const person & e) {
os << e.as_string();
return os;
}
+28
View File
@@ -0,0 +1,28 @@
#include <string>
#include <iostream>
#include <ostream>
#include <sstream>
using namespace std;
#pragma once
class person
{
private:
string name;
int age;
public:
person(){};
person(const string name, int age): name(name), age(age){};
string as_string() const;
void populate_data();
// you can define and declare in a header too:
inline int dummy_function() { return 42; };
// this is what allows us to do cout << my_person;
friend ostream & operator<<(ostream & os, const person & e);
};
+17
View File
@@ -0,0 +1,17 @@
!_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 //
CPPFLAGS Makefile /^CPPFLAGS=-Wall -g -std=c++0x$/;" m
age person.h /^ int age;$/;" m class:person
as_string person.cc /^string person::as_string() const$/;" f class:person
dummy_function person.h /^ inline int dummy_function() { return 42; };$/;" f class:person
main person-test.cc /^int main(int argc, char * argv[])$/;" f
name person.h /^ string name;$/;" m class:person
operator << person.cc /^ostream & operator<<(ostream & os, const person & e)$/;" f
person person.h /^ person(){};$/;" f class:person
person person.h /^ person(const string name, int age): name(name), age(age){};$/;" f class:person
person person.h /^class person$/;" c
populate_data person.cc /^void person::populate_data()$/;" f class:person
+10
View File
@@ -0,0 +1,10 @@
CXXFLAGS=-Wall -g
all: tuition
clean:
@rm -vf tuition
test: all
./tuition < test_run.txt
debug: all
gdb tuition
+12
View File
@@ -0,0 +1,12 @@
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>
using namespace std;
int main() {
double a;
cin >> a;
printf ("using printf %4.2f\n",a);
}
+27
View File
@@ -0,0 +1,27 @@
n
n
n
n
y
y
15
n
y
n
n
y
y
20
y
3
5
y
y
n
27
25
y
3
26
n
n
+237
View File
@@ -0,0 +1,237 @@
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdio>
using namespace std;
int TOTAL_INPUTS_CORRECT = 0;
int TOTAL_INVALID_INPUTS = 0;
struct student{
//making a struct of type student to facilitate the manipulation of data during this program
bool member_of_church;
double credit_hours;
double tuition;
};
void undergrad_or_not(student & s) {
//function determines if the student is doing an undergrad
string input;
cout << "Are you entering information about an undergraduate student (\"y\" or \"n\")? ";
cin >> input;
if(input == "y") {
TOTAL_INPUTS_CORRECT++;
}
else {
cout << "This program deals only with undergraduate students." << endl;
TOTAL_INVALID_INPUTS++;
undergrad_or_not(s);
}
}
bool check_credit_hours(double input) {
//checks the credit hours to make sure it is correct
double decimal = input - floor(input);//eliminate everything before the decimal to be able to evaulate
if(input > 25.0 or input < .5) {
cout << input << " is too small or too large for valid credit hour entry" << endl;
return false;
}
if(decimal == .0 or decimal == .5) {
return true;
}
else {
cout << "A student cannot enroll for " << input << " credit hours" << endl;
return false;
}
}
void get_credit_hours(student & s) {
//function to get the number of credit hours.
double input;
cout << "Credit hours winter 2012: ";
cin >> input;
if(check_credit_hours(input) == false) {
//using check_credit_hours function to determine if in range
TOTAL_INVALID_INPUTS++;
get_credit_hours(s);
}
else {
s.credit_hours = input;
TOTAL_INPUTS_CORRECT++;
}
}
void get_member_of_church(student & s) {
//function to determine if student is a member of the church
string input;
cout <<"Does the student belong to the LDS church (\"y\" or \"n\")? ";
cin >> input;
if(input == "n") {
s.member_of_church = false;
}
TOTAL_INPUTS_CORRECT++;
}
void calculate_tuition(student & s) {
//this determines the tuition based on credit hours
if(s.credit_hours > 12) {
if(s.member_of_church) {
s.tuition = 2280;
}
else {
s.tuition = 4560;
}
}
else if(s.credit_hours > 9 && s.credit_hours < 11.5) {
if(s.member_of_church) {
s.tuition = 2210;
}
else {
s.tuition = 4435;
}
}
else {
if(s.member_of_church) {
s.tuition = 234 * s.credit_hours;
}
else {
s.tuition = 468 * s.credit_hours;
}
}
cout << "Tuition is $" << s.tuition << " for winter 2012" << endl;
}
void calculate_refund(student & s) {
//used to calculate refund for student
string input;
cout << "Were there any classes that were dropped that need refund(\"y\" or \"n\")?";
cin >> input;
if(input == "y") {
int time_frame;
double credits_dropped;
double refund;
double new_tuition;
double old_tuition;
cout << "Which of the following dates best describes when you dropped the class(es)" << endl;
cout << "1) January 19, 2012\n2) January 23, 2012\n3) Feruary 27, 2012\n4) March 16, 2012" << endl;
cin >> time_frame;
cout << "How many credit hours were dropped?" << endl;
cin >> credits_dropped;
if(check_credit_hours(credits_dropped) == false or s.credit_hours-credits_dropped <= 0) {
cout << "this is an invalid credit hours, try again" << endl;
calculate_refund(s);
TOTAL_INVALID_INPUTS++;
}
else {
s.credit_hours = s.credit_hours - credits_dropped;
old_tuition = s.tuition;
calculate_tuition(s);
new_tuition = s.tuition;
if(time_frame == 1) {
refund = (old_tuition - new_tuition) *.85;
}
if(time_frame == 2) {
refund = (old_tuition - new_tuition) *.75;
}
if(time_frame == 3) {
refund = (old_tuition - new_tuition) *.50;
}
if(time_frame == 4) {
cout << "You wont get any money back. You dropped classes too late." << endl;
}
cout << refund << " is the amount you will be refunded" << endl;
s.tuition = s.tuition - refund;
printf ("This is the new tuition after refund %4.2f\n",s.tuition);
TOTAL_INPUTS_CORRECT++;
}
}
}
void get_max_tuition(vector<student> & students) {
//function to get the max tuition
double max_tuition = 0;
for(unsigned int i = 0; i < students.size();i++) {
if(max_tuition < students[i].tuition) {
max_tuition = students[i].tuition;
}
}
printf ("The highest tuition is $%4.2f\n" , max_tuition);
}
void get_min_tuition(vector<student> & students) {
//function to get min tuition
double min_tuition = 4560; //need to initilize the double to avoid error
for(unsigned int i = 0; i < students.size(); i++) { //made it the largest number it could be so this function
if(min_tuition > students[i].tuition) { //wont fail
min_tuition = students[i].tuition;
}
}
printf ("The lowest tuition is $%4.2f\n" , min_tuition);
}
void get_average_tuition(vector<student> & students) {
//function to get the average tuition for all students
double average = 0;
for(unsigned int i = 0; i < students.size(); i++) {
average += students[i].tuition;
}
average = average/students.size();
printf ("The average tuition is $%4.2f\n" , average);
}
void get_average_credit_hours(vector<student> & students) {
//function to get the average credit hours for all students
double average = 0;
for(unsigned int i = 0; i < students.size(); i++) {
average += students[i].credit_hours;
}
average = average/students.size();
printf ("This is the average credit hours %4.1f\n" , average);
}
void number_of_students(vector<student> & students) {
//function to report how many students were recorded
cout << "You entered valid information for " << students.size() << " students" << endl;
}
void percentage_of_correct_entries() {
//function reports percentage of correct entries
int percentage;
int total = TOTAL_INPUTS_CORRECT + TOTAL_INVALID_INPUTS;
percentage = TOTAL_INPUTS_CORRECT*100/total;
cout << percentage << "%" << " of your entries required no reprompting" << endl;
}
bool keep_playing() {
bool r = true;
string input;
cout << "Enter another student (\"y\" or \"n\")?";
cin >> input;
if(input == "n") {
r = false;
}
return r;
}
int main() {
bool keep_game = true;
vector<student> students;
//Keep the game going until person wants to quit
while(keep_game) {
student cur_student = {true, 0, 0};
undergrad_or_not(cur_student);
get_member_of_church(cur_student);
get_credit_hours(cur_student);
calculate_tuition(cur_student);
calculate_refund(cur_student);
students.push_back(cur_student);
keep_game = keep_playing();
}
number_of_students(students);
get_average_credit_hours(students);
get_average_tuition(students);
get_max_tuition(students);
get_min_tuition(students);
percentage_of_correct_entries();
}