UserA-UserB-UserC-UserD-UserF
Users connected by '-' know each other.
And I need an algorithm for these 2 tasks:
Is there an efficient solution?
EDIT
My purpose is not to prove it right or wrong,but to calculate the result real time when necessary.
Plus,I think the most expressive way is code,even pseudo ones.
EDIT AGAIN
I've decided that this kind of job must be done inside database,so it must be a sql solution!
The fastest O(n) algorithm for six-degrees of separation would probably be finding the sets of all users 1-step away from UserX and UserY, and finding the intersection of those two sets. If none, then add the users 2-steps from UserX and intersect; then add users 2-steps from UserY and intersect; etc. up to 3.
In order to calculate the average degree of separation between the nodes in a graph, we consider one node in each of the steps, calculate the average and multiply it with the total number of nodes in that step.
Six degrees of separation is the theory that any person on the planet can be connected to any other person on the planet through a chain of acquaintances that has no more than five intermediaries.
Represent this list of users by a graph
- Calculate the path from UserX to UserY
- For UserX,calculate all users that is no more than 3 steps away.
These questions are so closely related that the same algorithm actually solves both of them. You can call it "Dijkstra's algorithm with all edges having weight 1," or "breadth-first search."
Essentially, starting at the first node, visit all its relatives; then mark them all as visited, record the shortest path to each (the shortest path to them + the edge you just traversed), and repeat for each of them. Stop after you've reached your destination for Problem #1, stop after the shortest path is > 3 for Problem #2.
The fastest O(n) algorithm for six-degrees of separation would probably be finding the sets of all users 1-step away from UserX and UserY, and finding the intersection of those two sets. If none, then add the users 2-steps from UserX and intersect; then add users 2-steps from UserY and intersect; etc. up to 3.
If each person has an average of 100 friends, this could require looking at up to about 2,020,200 users, as opposed to the 1,010 billion for Dijkstra's algorithm. In practice, these numbers would be much smaller, since often two of your friends are also friends with each other.
This is the only method of solving six-degrees of separation (of those mentioned so far) that will work in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With