1
1
// https://www.codewars.com/kata/53697be005f803751e0015aa
2
- // write finction to replace all the lowercase vowels in a given string with numbers and function to turn to back
2
+ // write function to replace all the lowercase vowels in a given string with numbers and function to turn to back
3
3
#include < string>
4
- #include < iostream>
5
4
#include < algorithm>
5
+ #include < unordered_map>
6
6
7
+ std::unordered_map<char , char > replacements = {
8
+ {' a' , 1 },
9
+ {' e' , 2 },
10
+ {' i' , 3 },
11
+ {' o' , 4 },
12
+ {' u' , 5 },
13
+ {1 , ' a' },
14
+ {2 , ' e' },
15
+ {3 , ' i' },
16
+ {4 , ' o' },
17
+ {5 , ' u' }
18
+ };
7
19
8
20
std::string encode (const std::string &str) {
9
- char encoded_symbol = 49 ; // 49 is ascii code of digit "1"
10
- std::string res = str;
11
- for (auto symbol : {' a' ,' e' ,' i' ,' o' ,' u' }){
12
- std::replace (res.begin (), res.end (), symbol, encoded_symbol);
13
- encoded_symbol++;
14
- }
15
- return res;
21
+ return impl (str, replacements);
16
22
}
17
23
18
24
19
25
std::string decode (const std::string &str) {
20
- char decoded_symbol = 49 ;
21
- std::string res = str;
22
- for (auto symbol : {' a' ,' e' ,' i' ,' o' ,' u' }){
23
- std::replace (res.begin (), res.end (), decoded_symbol, symbol);
24
- decoded_symbol++;
25
- }
26
- return res;
27
- };
26
+ return impl (str, replacements);
27
+ };
28
+
29
+ std::string impl (const std::string& str, const std::unordered_map<char , char >& repl) {
30
+ std::string output{str};
31
+ std::for_each (output.begin (), output.end (), [&repl](char & ch) {
32
+ if (repl.find (ch) != repl.end ()) {
33
+ ch = repl.at (ch);
34
+ }
35
+ });
36
+ return output;
37
+ }
0 commit comments