Problem
Write a method to sort an array of strings so that all the anagrams are next to each other.
Solution
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool is_anagram(string &s1, string &s2)
{
vector<char> v1, v2;
v1.assign(s1.begin(),s1.end());
v2.assign(s2.begin(),s2.end());
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
return (v1 == v2);
}
void print_strings(vector<string> &v)
{
copy(v.begin(), v.end(),ostream_iterator<string>(cout, " "));
cout << endl;
}
void sort_strings(vector<string> &v)
{
sort(v.begin(), v.end());
int i, j;
int len = v.size();
for(i = 0; i < len ;i ++ ){
for( j = i + 1; j < len; j ++){
if(is_anagram(v.at(i), v.at(j))){
string s = v.at(j);
v.erase(v.begin() + j);
i ++;
v.insert(v.begin() + i, s);
}
}
}
}
int main(int argc, char* argv[])
{
vector<string> v;
v.push_back("I");
v.push_back("yum");
v.push_back("can");
v.push_back("eat");
v.push_back("I");
v.push_back("ate");
v.push_back("att");
v.push_back("I");
v.push_back("the");
v.push_back("eel");
v.push_back("eth");
v.push_back("het");
cout << "before sort" << endl;
print_strings(v);
sort_strings(v);
cout << "after sort" << endl;
print_strings(v);
return 0;
}
Output
before sort
I yum can eat I ate att I the eel eth het
after sort
I I I ate eat att can eel eth het the yum