Debian Codegraph @

CodeLite/clAnagram.cpp

raw
1 #include "clAnagram.h"
2 #include <algorithm>
3 #include <wx/wxcrt.h>
4
5 #define IS_WHITESPACE(ch) (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
6
7 clAnagram::clAnagram(const wxString& needle, size_t flags)
8 : m_flags(flags)
9 {
10 Reset(needle, m_flags);
11 }
12
13 clAnagram::~clAnagram() {}
14
15 bool clAnagram::Matches(const wxString& haystack) const
16 {
17 std::unordered_map<wxChar, int> charsCount = m_charCounts;
18 for(size_t i = 0; i < haystack.size(); ++i) {
19 wxChar ch = haystack[i];
20 ch = wxTolower(ch);
21 if(charsCount.count(ch)) {
22 int& counter = charsCount[ch];
23 counter--;
24 if(counter == 0) { charsCount.erase(ch); }
25 if(charsCount.empty()) { return true; }
26 }
27 }
28 return false;
29 }
30
31 bool clAnagram::MatchesInOrder(const wxString& haystack) const
32 {
33 if(m_needle.IsEmpty()) { return true; }
34 size_t index = 0;
35 size_t maxIndex = m_needle.size();
36 for(size_t i = 0; i < haystack.size(); ++i) {
37 wxChar ch = haystack[i];
38 ch = wxTolower(ch);
39 if(ch == m_needle[index]) { ++index; }
40 if(maxIndex == index) { return true; }
41 }
42 return false;
43 }
44
45 void clAnagram::Reset(const wxString& needle, size_t flags)
46 {
47 m_flags = flags;
48 m_needle.Clear();
49 if(HasFlag(eAnagramFlag::kIgnoreWhitespace)) {
50 for(size_t i = 0; i < needle.size(); ++i) {
51 wxChar ch = needle[i];
52 if(IS_WHITESPACE(ch)) { continue; }
53 m_needle.Append(wxTolower(ch));
54 }
55 } else {
56 m_needle = needle.Lower();
57 }
58
59 m_charCounts.clear();
60 std::for_each(m_needle.begin(), m_needle.end(), [&](wxChar ch) {
61 if(m_charCounts.count(ch) == 0) {
62 m_charCounts[ch] = 1;
63 } else {
64 m_charCounts[ch]++;
65 }
66 });
67 }
68
69 bool clAnagram::IsEmpty() const { return m_needle.IsEmpty(); }