Thursday, July 28, 2016

Ranked Cources, Use of PriorityQueue

Assuming getDirectFriendsForUser returns a list of direct friends in social network, assuming getAttendedCourcesForUser returns a list of courses an user is attending. Try to suggest courses according to its polularity.

I use HashMap to collect statistics of course popularity, and then sorting courses according to their polularity with priority queue.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 public List<String> getRankedCourses(String user) {
  List<String> rankedCourses = new LinkedList<String>();
  // find all first level and second level friends
  Set<String> friends = new HashSet<String>();
  // 1. direct friends
  List<String> directFriends = getDirectFriendsForUser(user);
  friends.addAll(directFriends);
  // 2. second level friends
  for (String friend : directFriends) {
   if (!user.equals(friend)) {// not need to process user again
    friends.addAll(getDirectFriendsForUser(friend));
   }
  }
  friends.remove(user);
  // course statistics
  Map<String, Integer> courseStats = new HashMap<String, Integer>();
  // for each of friend, collect statistics of their courses
  for (String friend : friends) {
   for (String course : getAttendedCoursesForUser(friend)) {
    if (courseStats.get(course) == null) {
     courseStats.put(course, 1);
    } else {
     courseStats.put(course, courseStats.get(course) + 1);
    }
   }
  }
  // use priority queue to sort the map.entry in order to return a list of
  // cources according to their popularity
  PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<Map.Entry<String, Integer>>(
    courseStats.size(),
    new Comparator<Map.Entry<String, Integer>>() {
     public int compare(Map.Entry<String, Integer> e1,
       Map.Entry<String, Integer> e2) {
      return e2.getValue() - e1.getValue();
     }
    });
  // adding entries to pq
  for (Map.Entry<String, Integer> e : courseStats.entrySet()) {
   pq.add(e);
  }
  // prepare result list
  while (!pq.isEmpty()) {
   rankedCourses.add(pq.poll().getKey());// key from map.entry is the
             // course name
  }
  // excluding user's own cources
  rankedCourses.removeAll(getAttendedCoursesForUser(user));
  return rankedCourses;
 }

No comments: