← Back to puzzles

008 A Family Affair

You are a lord in a dark fantasy universe trying to figure out some questionable family relations, so you visit the royal archives to read the family chronicles. Unfortunately, someone has attempted to burn down the archives! Looks like they had some secret they wanted to protect.

Fortunately, some fragments of the chronicles are still readable; can you reconstruct the family tree based on these fragments?

A fragment is of the form "X, the R of Y", where X and Y are names, and R is their relationship; for example "Ned, the father of Brandon" or "Robb, the brother of Sansa".

The different possible relationships are:

You can assume that brothers and sisters will always have the same mother and father, and that two different people will not have the same name.

Your task is to write a program that, given lines of the form "X, the R of Y", prints a list of each person and their children of the form "Person - Child A, Child B, ..." (where both the persons and their children should be sorted alphabetically). If a person has no children, you should just print their name.

For example, given the input:

Ned, the father of Robb
Catelyn, the mother of Sansa
Robb, the brother of Sansa

The output should be:

Catelyn - Robb, Sansa
Ned - Robb, Sansa
Robb
Sansa

Another example—given the input:

Rhaegar, the brother of Viserys
Viserys, the brother of Daenerys
Aerys, the father of Rhaegar
Rhaella, the mother of Rhaegar
Jaehaerys, the father of Aerys
Shaera, the mother of Aerys

The output should be:

Aerys - Daenerys, Rhaegar, Viserys
Daenerys
Jaehaerys - Aerys
Rhaegar
Rhaella - Daenerys, Rhaegar, Viserys
Shaera - Aerys
Viserys

Good luck on your quest, brave lord!