Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Travel Buddy
/***************************************************************************** * 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. * ****************************************************************************/ #include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; class Buddy { public: Buddy(string nameV, vector<string>& list): name(nameV),similarity(0) { cities = set<string>(list.begin(), list.end()); } string name; int similarity; set<string> cities; // a list of city names int similar(Buddy& buddy){ int n = 0; for(string city: cities){ if(buddy.cities.count(city)) n++; } // change to percentile double per = 100.0 * n / cities.size(); similarity = (int) per; return (int)per; } }; bool Mycompare(Buddy* a, Buddy* b){ return a->similarity > b->similarity; } class Match { public: Buddy* my; vector<Buddy*> buddies; public: Match(Buddy& myself, vector<Buddy>& v){ my = &myself; for(int i = 0; i<(int)v.size(); i++){ if(v[i].similar(*my) >= 50) buddies.push_back(&v[i]); } } vector<Buddy*> getSortedBuddies(){ sort(buddies.begin(), buddies.end(), Mycompare); return vector<Buddy*>(buddies); // making a copy } vector<string> getRecommendedCity(int n){ set<string> res; sort(buddies.begin(), buddies.end(), Mycompare); // make sure it is sorted for(int i =0; i<buddies.size(); i++){ Buddy* b = buddies[i]; for(auto city: b->cities){ if(my->cities.count(city) == 0) res.insert(city); if(res.size() == n) return vector<string>(res.begin(), res.end()); } } return vector<string>(res.begin(), res.end()); } }; int main(){ // create a list of wish-lists vector<string> list0 = {"a", "b", "c", "d"}; vector<string> list1 = {"a", "b", "e", "f"}; vector<string> list2 = {"a", "c", "d", "g"}; vector<string> list3 = {"c", "f", "e", "g"}; //create a Buddy vector vector<Buddy> v; v.push_back(Buddy("B1", list1)); v.push_back(Buddy("B2", list2)); v.push_back(Buddy("B3", list3)); Buddy myself("me", list0); Match match(myself, v); // print buddy list vector<Buddy*> result = match.getSortedBuddies(); cout << "My buddies in order: " << endl; for(auto p: result){ cout << p->name << " : " << p->similarity << endl; } // print recommended cities vector<string> cities = match.getRecommendedCity(2); cout << "Recommended cities (n=2): " << endl; for(auto x: cities) cout << x << endl; cout << endl; cities = match.getRecommendedCity(5); cout << "Recommended cities (n=5): " << endl; for(auto x: cities) cout << x << endl; return 0; }
run
|
edit
|
history
|
help
0
HTML Node
Lotto random number game {modify}
cppPyClassMethod
задача new
designated-inits
Dulce enredo p1
append
HeapSort
MeanSDVar
Project Euler - 113