I'm currently working on a problem where I have to find friendship chains via recursion in Java. Statistically, a person knows another person over about 6 waypoints - which is the chain I am trying to find.
I've got a class "Person", which defines a name and direct friends:
public class Person
{
private Person[] friendChain;
private String name;
public Person(String name, Person[] friendChain)
{
this.friendChain = friendChain;
this.name = name;
}
public Person[] getFriends()
{
return this.friendChain;
}
public String getName()
{
return this.name;
}
public boolean isFriendWith(Person person)
{
for(Person p: this.friendChain)
{
if(p != null && person != null && p.getName().equals(person.getName()))
return true;
}
return false;
}
public boolean equals (Person person)
{
return this.name.equals(person.getName());
}
public String toString()
{
return this.getName();
}
}
A diagram was given that gives an example chain, where arrows indicate a one-way or two-way relationship (as in Thomas knows Theresa, but Theresa doesn't know Thomas):
So basically my outcome should look similiar to something like this:
result = getFriendshipChain(adam, theresa);
result[0].getName(); // "Michael"
result[1].getName(); // "Kerstin"
result[2].getName(); // "Thomas"
result[3].getName(); // "Theresa"
result[4].getName(); // null
result[5].getName(); // null
I've done a lot of recursive programming in the past, but I just can't get my head into this right now - I'd appreciate any help!