Guest User

Untitled

a guest
May 20th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. /**
  2.      * Takes two persons and looks at their friends. If p1 is befriended with p2,
  3.      * or if p1 knows someone who is befriended with p2 over any number of friends,
  4.      * returns true.
  5.      * @param p1 The first Person
  6.      * @param p2 The second Person
  7.      * @return Returns whether p1 and p2 are connected over a chain of friendships.
  8.      */
  9.     public boolean areConnected(Person p1, Person p2) {
  10.         boolean areConnected = false;
  11.         if (p1 != null && p2 != null) {
  12.             PersonProfile from = getProfile(p1);
  13.             PersonProfile to = getProfile(p2);
  14.             areConnected = areConnected(from, to, null);
  15.         }
  16.         return areConnected;
  17.     }
  18.     /**
  19.      * Recursive working method for areConnected(Person, Person)
  20.      * @param from Profile to find a chain from.
  21.      * @param to Profile to find a chain to.
  22.      * @param master 'from' from the next higher instance. Is null on first call.
  23.      * @return Returns whether from and to are connected.
  24.      */
  25.     private boolean areConnected(PersonProfile from, PersonProfile to, PersonProfile master) {
  26.         boolean areConnected = false;
  27.         if (from.isBefriendedWith(to)) {
  28.             areConnected = true;
  29.         } else {
  30.             PersonProfile[] friends = from.getFriends();
  31.             for (int i = 0; i < friends.length && areConnected == false; i++) {
  32.                 if (!(friends[i] == master || friends[i].isBefriendedWith(master))) {
  33.                     areConnected = areConnected(friends[i], to, from);
  34.                 }
  35.             }
  36.         }
  37.         return areConnected;
  38.     }
Add Comment
Please, Sign In to add comment