-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscrambled_input.cpp
More file actions
98 lines (90 loc) · 2.72 KB
/
Copy pathscrambled_input.cpp
File metadata and controls
98 lines (90 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <string>
#include <unordered_map>
#include <algorithm>
#include <optional>
#include <iostream>
#include <vector>
void initializeOrderAgnosticDictionary(const std::vector<std::string>& dictionary, std::unordered_map<std::string, std::string>& orderAgnosticDictionary) {
for (const auto& word : dictionary) {
auto sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
auto it = orderAgnosticDictionary.find(sortedWord);
if (it == orderAgnosticDictionary.end()) {
orderAgnosticDictionary.emplace(sortedWord, word);
}
}
}
std::vector<std::string> splitIntoWords(const std::string& sentence) {
std::vector<std::string> words;
if (sentence.empty()) {
return words;
}
auto* begin = &sentence[0];
auto* end = &sentence[sentence.size()];
for (; end > begin; --end) {
if (*(end - 1) != ' ') {
break;
}
}
auto* it1 = begin, *it2 = begin;
for (; it1 != end; ++it1) {
if (*it1 == ' ') {
if (it1 != it2) {
words.emplace_back(std::string(it2, it1));
}
it2 = it1;
} else if (*it2 == ' ') {
it2 = it1;
}
}
if (it1 != it2) {
words.emplace_back(std::string(it2, end));
}
return words;
}
std::optional<std::vector<std::string>> unscramble(const std::unordered_map<std::string, std::string>& orderAgnosticDictionary,
const std::string& scrambled) {
std::vector<std::string> output;
auto words = splitIntoWords(scrambled);
for (auto& word : words) {
auto sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
auto it = orderAgnosticDictionary.find(sortedWord);
if (it != orderAgnosticDictionary.end()) {
output.emplace_back(it->second);
} else {
return std::nullopt;
}
}
return output;
}
std::string concatenate(const std::optional<std::vector<std::string>>& words) {
std::string sentence;
if (words != std::nullopt) {
for (auto& word : *words) {
sentence += word + " ";
}
}
return sentence;
}
void test(const char* name, const std::unordered_map<std::string, std::string>& orderAgnosticDictionary, const std::string& scrambled) {
std::cout << name << " = " << concatenate(unscramble(orderAgnosticDictionary, scrambled)) << std::endl;
}
int main() {
std::unordered_map<std::string, std::string> dict;
initializeOrderAgnosticDictionary(
{
"this",
"is",
"a",
"sample"
},
dict
);
test(
"statement example",
dict,
"thsi si a emplas "
);
return 0;
}