Created
November 6, 2015 13:08
-
-
Save goyusia/fefbfa42ccc3ec3907d2 to your computer and use it in GitHub Desktop.
Calculate Average of "Hello, World!".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| Calculate Average of "Hello, World!". | |
| $ clang++ hello_world.cpp -std=c++11 | |
| $ ./a.out | |
| Rello, aorld | |
| 82 101 108 108 111 44 32 97 111 114 108 100 22 3 0 | |
| */ | |
| #include <string> | |
| #include <cstdio> | |
| #include <array> | |
| #include <vector> | |
| #include <algorithm> | |
| #include <sstream> | |
| std::array<std::string, 3> candidates = { | |
| std::string("hello, world"), | |
| std::string("Hello, World!"), | |
| std::string("Hello, World!\n"), | |
| }; | |
| int main() | |
| { | |
| auto length_comp_func = [](const std::string &a, const std::string &b) { | |
| return a.length() < b.length(); | |
| }; | |
| auto max_len_elem = std::max_element(candidates.begin(), candidates.end(), length_comp_func); | |
| std::vector<int> char_buffer(max_len_elem->length() + 1, 0); | |
| for(auto candidate : candidates) { | |
| for(int i = 0 ; i < candidate.length() ; ++i) { | |
| char_buffer[i] += candidate[i]; | |
| } | |
| } | |
| std::ostringstream oss; | |
| for(auto sum : char_buffer) { | |
| char ch = (char)((float)sum / candidates.size()); | |
| oss << ch; | |
| } | |
| auto average_solution = oss.str(); | |
| printf("%s\n", average_solution.data()); | |
| for(auto ch : average_solution) { | |
| printf("%d ", ch); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment