tags:

views:

110

answers:

3

What would be the best algorithm for the undermentioned problem.

Implement method PrintFamilyTree() that prints out the Name and Generation of the tree
Output should resemble
Name: Jan Generation:0
Name: Mike Generation:1
Name: Greg Generation:2
Name: Carol: Generation: 2
Name: Peter Generation: 3
Name: Marcia Generation: 3
Name: Bobby Generation: 1

class Human : public std::vector<Human *>
{
public:
Human(const std::string &name) : m_Name(name) {};
virtual void PrintFamilyTree(const short &generation = 0) const;
protected:
std::string m_Name;
};

class Male: public Human
{
public:
Male(const std::string &name) : Human(name) {};
};

class Female: public Human
{
public:
Female(const std::string &name) : Human(name) {};
};

void main()
{
Male m1("Mike"), m2("Greg"), m3("Peter"), m4("Bobby");
Female f1("Carol"), f2("Marcia"), f3("Jan");

m1.push_back(&m2);
f1.push_back(&m3);
f1.push_back(&f2);
m1.push_back(&f1);
f3.push_back(&m1);
f3.push_back(&m4);

f3.PrintFamilyTree();
}
+5  A: 
class Human : public std::vector<Human *>

Not a good idea -- STL containers are typically not designed to be derived from. Think of containment rather than inheritance.

void main()

main returns an int. Always.

This looks like a straight-forward problem. Think of a tree-like structure. You may want to change the container you are using (i.e. vector) to something more suitable.

Be warned, your question smells a lot like homework, so there'd be few responses!

dirkgently
A: 
  1. Print the name and generation for the starting object
  2. For each child object, print their name and generation.
  3. For each child object (the same list of children as line 2), print their tree by starting at line 2 with the child object's children
Dathan
+1  A: 

For the algorithm I think a Topological sort will fit, but you need a graph not a vector

fabrizioM