For example i have a person class, it has name and acquaintance properties, name is string while acquaintance is array of persons. I would like to write a method which receives a name as param and find it the name in person's acquaintance list and acquaintances of acquaintance list and so on, deep until person acquaintance is null or name is found.
Following is the code. Also there can be circular loop, how to avoid that. Thanks in advance for your interest in the question.
class P
{
public string Name;
public P[] Acquaintances;
public P(string name, P[] acquaintances)
{
if (String.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Name cannot be null or white space.",
"name");
}
this.Name = name;
this.Acquaintances = acquaintances;
}
public bool FindAcquaintance(string name)
{
if (String.IsNullOrWhiteSpace(name))
{
throw new ArgumentException("Name cannot be null or white space.",
"name");
}
if (Name.Equals(name))
{
return true;
}
if (Acquaintances == null || Acquaintances.Length == 0)
{
return false;
}
foreach (P acquaintance in this.Acquaintances)
{
if (acquaintance.Name.Equals(name))
{
return true;
}
if (acquaintance.FindAcquaintance(name))
{
return true;
}
}
return false;
}
}
Usage
P person = new P("Alex",
new P[] {
new P("Bob", new P[] { new P("James", new P[] { }) }),
new P("Kavin", new P[] { new P("Brent", null) })
});
bool found = person.FindAcquaintance("Brent");