anagram: naive approach, iteration 1

This commit is contained in:
Dmitry Kokorin 2016-02-25 23:14:03 +03:00
parent c874827624
commit 704eff347e
2 changed files with 29 additions and 26 deletions

View file

@ -1,8 +1,6 @@
#include "anagram.h"
#include <algorithm>
#include <locale>
#include <iostream>
namespace anagram {
@ -11,45 +9,48 @@ namespace anagram {
using namespace std;
static inline string normalize(const string &str)
namespace {
struct Helper
{
string result = str;
Helper(const string &str, const locale &loc)
{
lowercase = str;
transform(lowercase.begin(), lowercase.end(),
lowercase.begin(), [=](char c){return tolower(c, loc);});
transform(result.begin(), result.end(),
result.begin(),
[](char c){return tolower(c);});
normalized = lowercase;
sort(normalized.begin(), normalized.end());
}
sort(result.begin(), result.end());
string lowercase;
string normalized;
};
cout << str << " -> " << result << endl;
return result;
}
anagram::anagram(const string &_key)
: key(_key)
{
cout << "New test, key=" << _key << endl;
key = normalize(_key);
}
StringContainer
anagram::matches(const StringContainer &input) const
anagram::matches(const StringContainer &input,
const locale &loc) const
{
StringContainer result(input.size());
cout << "Input: {";
for (auto s : input)
cout << s << " ";
cout << "}" << endl;
const Helper key_helper(key, loc);
auto is_anagram = [=](const string &str) {
Helper helper(str, loc);
return helper.normalized == key_helper.normalized
&& helper.lowercase != key_helper.lowercase;
};
auto iter = copy_if(input.cbegin(), input.cend(),
result.begin(),
[=](const string &s){return key == normalize(s);});
cout << "Output: {";
for (auto s : result)
cout << s << " ";
cout << "}" << endl;
result.begin(), is_anagram);
result.resize(distance(result.begin(), iter));

View file

@ -3,6 +3,7 @@
#define EXERCISM_RUN_ALL_TESTS
#include <list>
#include <locale>
#include <string>
@ -19,7 +20,8 @@ public:
anagram(const std::string &_key);
StringContainer matches(const StringContainer &input) const;
StringContainer matches(const StringContainer &input,
const std::locale &locale = std::locale()) const;
};
}