Travel Buddy

I have a wish list of cities that I want to visit to, my friends also have city wish lists that they want to visit to. If one of my friends share more than 50% (over his city count in his wish list), he is my buddy.

Given a list of city wish list, output buddy list sorting by similarity.
这题比较简单吧。
没什么好说的。
主要就是OOD?

public class TravelBuddy {
    Set myWishList;
    List buddyList;
    public TravelBuddy(Set myWishList, Map> friendWishList) {
        this.myWishList = myWishList;
        buddyList = new ArrayList<>();


        for (Map.Entry> entry : friendWishList.entrySet()) {
            String name = entry.getKey();
            Set set = entry.getValue();
            int count = 0;
            for (String city : set) {
                if (myWishList.contains(city)) count++;
            }
            double simliarity = myWishList.size() != 0 ? 1.0 * count / myWishList.size() : 0.0;
            if (simliarity < 0.5) continue;
            buddyList.add(new Buddy(name, simliarity, set ));
        }
    }
    public List  getSortedBuddies(){

        Collections.sort(buddyList);

        List ans = new ArrayList<>();
        for (Buddy b : buddyList) {
            ans.add(b.name);
        }
        return ans;
    }
    public List recommendCities(int k) {
        List ans = new ArrayList<>();
        int index = 0;
        while (ans.size() < k && index < buddyList.size()) {
            Set bWishList = buddyList.get(index++).wishList;
            for (String city : bWishList) {
                if (myWishList.contains(city)) continue;
                ans.add(city);
                if (ans.size() == k) break;
            }

        }
        return ans;
    }

    class Buddy implements Comparable {

        String name;
        double similarity;
        Set wishList;

        Buddy(String name, double similarity, Set wishList) {
            this.name = name;
            this.similarity = similarity;
            this.wishList = wishList;
        }

        @Override
        public int compareTo(Buddy that) {
            if (this.similarity > that.similarity) return -1;
            if (this.similarity == that.similarity) return 0;
            return 1;
        }
    }

你可能感兴趣的:(Travel Buddy)