Created
August 16, 2016 12:50
-
-
Save itayB/8e6d49268cec63263c57b493afbea11c to your computer and use it in GitHub Desktop.
Compare names for smart matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <set> | |
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
#include <sstream> | |
using namespace std; | |
void split(const string &s, char delim, vector<string> &elems) { | |
stringstream ss(s); | |
string item; | |
while (getline(ss, item, delim)) { | |
elems.push_back(item); | |
} | |
} | |
bool match(string& a, string& b) { | |
return a.compare(b) == 0 || | |
((a.size() == 1 || b.size() == 1) && a[0] == b[0]); | |
} | |
bool isEqual(string s1, string s2) { | |
// move both string to upper case | |
transform(s1.begin(), s1.end(), s1.begin(), ::toupper); | |
transform(s2.begin(), s2.end(), s2.begin(), ::toupper); | |
vector<string> s1vector; | |
vector<string> s2vector; | |
split(s1, ' ', s1vector); | |
split(s2, ' ', s2vector); | |
if (s1vector.size() < s2vector.size()) { | |
s1vector.swap(s2vector); | |
} | |
int j=0; | |
for (int i=0 ; i < s1vector.size() && j < s2vector.size() ; i++) { | |
if (match(s1vector[i], s2vector[j])) { | |
j++; | |
} | |
} | |
return j == s2vector.size(); | |
} | |
void test(string s1, string s2) { | |
cout << s1 << (isEqual(s1,s2) ? "=" : "!=") << s2 << endl; | |
} | |
int main() { | |
// Should be equal | |
test("John Fitzgerald Kennedy", "John K"); | |
test("John Fitzgerald", "J F K"); | |
test("J F K", "John Fitzgerald"); | |
test("John Fitzgerald K","J F K"); | |
test("John Fitzgerald K","J F Kennedy"); | |
test("John Fitzgerald K","JOHN F Kennedy"); | |
// Shouldn't be equal | |
test("John K Fitzgerald","J F Kennedy"); | |
test("John Fitzgerald K","Jon"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment