I usually don't write the type of code to find users within two degrees, so I thought it'd be a fun exercise in my fun-time language, Python.
And did you mean users instead of friends? If a user is already a friend with someone, that means they can only be one degree away.
Here's what I came up with. Is this about right?
# Set up a mock DB holding users and relationships.
# 1 is 1 degree from 2, 5 and 6
# 1 is 2 degrees from 3, 4, 6
# 1 is 3 degrees from 7 and 8
# 1 is 4 degrees from 7 and 8
people_store = [''] #0 -- put blank in 0 so we can have a one-based list.
people_store.append([2,5,6]) #1
people_store.append([1,3]) #2
people_store.append([2,4,6]) #3
people_store.append([3,6,7,8]) #4
people_store.append([1]) #5
people_store.append([1,3,4]) #6
people_store.append([4,8]) #7
people_store.append([4,7,9]) #8
people_store.append([8]) #9
def find_users_within_x_degrees(user_id, degrees):
"""Given a user ID, find other users within two degrees."""
# Users that are within the degree range.
# Start by adding current user's friends (1 degree).
users_within_range = set(people_store[user_id])
# Keep track of user IDs that have been checked.
checked_ids = set()
# Start at 2, because we have already handled 1 degree above.
for degree in range(2, degrees+1):
# Get other users IDs and get their friends. Only do so for users we haven't checked.
for other_user_id in users_within_range.difference(checked_ids):
checked_ids.add(other_user_id)
# Add other user's friends.
users_within_range.update(people_store[other_user_id])
# Because friendships are reciprocal, if the number of degrees is > 1, the requested user_id will be in the set, and should be removed.
if degrees > 1:
users_within_range.remove(user_id)
return users_within_range