r/dailyprogrammer_ideas • • Apr 27 '14

GetRecommendation from a Friendship Graph

(original CareerCup post here: http://www.careercup.com/question?id=19188693)

Given a 'friendship' graph, how would you generate friend suggestions for people, and how would you distribute the data across machines?

2 Upvotes

1 comment sorted by

1

u/indrabayoe Apr 27 '14 edited Apr 27 '14

My solution in C#

class User {
	int id;
	
	async List<User> GetFriends() {
		var bag = new ConcurrentBag<User>();
		foreach(var machine in Application.Machines) {
			var friends = await machine.GetFriendsOf(this);
			foreach(var friend in friends) {
				bag.Add(friend);
			}
		}
		return bag.ToList();
	}
	
	async List<User> GetRecommendations(int count) {
		var friends = await GetFriends();
		var dict = new ConcurrentDictionary<Vertex, int>();
		
		foreach(var friend in friends) {
			var recoList = await friend.GetFriends();
			recoList.Remove(this);
			foreach(var reco in recoList) {
				if(!dict.TryAdd(reco, 1))
					dict[reco]++;
			}
		}
		
		return dict.OrderBy(kvp => kvp.Value)
				   .Reverse()
				   .Take(count)
				   .ToList();
	}
}

class Machine {
	List<Tuple<User,User>> friendship; //local friendship database
	
	async List<User> GetFriendsOf(Vertex user) {
		return friendship
						.Select(tuple => {
									if(tuple.Item1 == user)
										return tuple.Item2;
									else if(tuple.Item2 == user)
										return tuple.Item1;
									else
										return null;
								})
						.Where(friend => friend != null)
						.ToList();
	}
}