-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathperson.cpp
82 lines (70 loc) · 2.11 KB
/
person.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "person.h"
#include <iostream>
#include <string.h>
using std::cout;
using std::endl;
Person::Person(const char *name_, Person* father_, Person* mother_){
name = new char[strlen(name_)];
strcpy(name, name_);
father = father_;
mother = mother_;
capacity = 1;
numChildren = 0;
children = new Person*[capacity];
}
Person::~Person(){
delete children;
}
void Person::addChild(Person *newChild){
if(numChildren == capacity) expand(&children, &capacity);
children[numChildren++] = newChild;
}
void Person::printAncestors(){
cout << endl << "Ancestors of " << name << endl;
printLineage('u', 0);
}
void Person::printDecendents(){
cout << endl << "Decendents of " << name << endl;
printLineage('d', 0);
}
void Person::printLineage(char dir, int level){
char *temp = compute_relation(level);
if(dir == 'd'){
for(int i = 0; i < numChildren; i++){
cout << temp << "child: " << children[i]->getName() << endl;
children[i]->printLineage(dir, level + 1);
}
} else {
if(mother){
cout << temp << "mother: " << mother->getName() << endl;
mother->printLineage(dir, level + 1);
}
if(father){
cout << temp << "father: " << father->getName() << endl;
father->printLineage(dir, level + 1);
}
}
}
/* helper function to compute the lineage
* if level = 0 then returns the empty string
* if level >= 1 then returns ("great ")^(level - 1) + "grand "
*/
char* Person::compute_relation(int level){
if(level == 0) return strcpy(new char[1], "");
char *temp = strcpy(new char[strlen("grand ") + 1], "grand ");;
for(int i = 2; i <= level; i++){
char *temp2 = new char[strlen("great ") + strlen(temp) + 1];
strcat(strcpy(temp2, "great "), temp);
temp = temp2;
}
return temp;
}
/* non-member function which doubles the size of t
* NOTE: t's type will be a pointer to an array of pointers
*/
void expand(Person ***t, int *MAX){
Person **temp = new Person*[2 * *MAX];
memcpy(temp, *t, *MAX * sizeof(**t));
*MAX *= 2;
*t = temp;
}