diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/day15.cpp | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/day15.cpp b/src/day15.cpp new file mode 100644 index 0000000..905110f --- /dev/null +++ b/src/day15.cpp | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | #include <fstream> | ||
| 2 | #include <iostream> | ||
| 3 | #include <sstream> | ||
| 4 | #include <string> | ||
| 5 | #include <vector> | ||
| 6 | using namespace std; | ||
| 7 | |||
| 8 | string | ||
| 9 | read_file(string_view filename) | ||
| 10 | { | ||
| 11 | fstream input{ filename }; | ||
| 12 | return { istreambuf_iterator<char>{ input }, istreambuf_iterator<char>{} }; | ||
| 13 | } | ||
| 14 | |||
| 15 | inline string& | ||
| 16 | rtrim(string& s, const char* t = " \t\n\r\f\v") | ||
| 17 | { | ||
| 18 | s.erase(s.find_last_not_of(t) + 1); | ||
| 19 | return s; | ||
| 20 | } | ||
| 21 | |||
| 22 | vector<string> | ||
| 23 | split(const string& line, char sep) | ||
| 24 | { | ||
| 25 | vector<string> parts{}; | ||
| 26 | stringstream input{ line }; | ||
| 27 | |||
| 28 | for ( string part; getline(input, part, sep); ) { | ||
| 29 | parts.emplace_back(rtrim(part)); | ||
| 30 | } | ||
| 31 | |||
| 32 | return parts; | ||
| 33 | } | ||
| 34 | |||
| 35 | unsigned int | ||
| 36 | calculate_hash(string_view str) | ||
| 37 | { | ||
| 38 | unsigned int value = 0; | ||
| 39 | for ( auto chr: str ) { | ||
| 40 | value += static_cast<unsigned char>(chr); | ||
| 41 | value *= 17; | ||
| 42 | } | ||
| 43 | return value % 256; | ||
| 44 | } | ||
| 45 | |||
| 46 | void | ||
| 47 | part1() | ||
| 48 | { | ||
| 49 | const auto line = read_file("data/day15.txt"); | ||
| 50 | const auto parts = split(line, ','); | ||
| 51 | unsigned long value = 0; | ||
| 52 | for ( const auto& part: parts ) { | ||
| 53 | value += calculate_hash(part); | ||
| 54 | } | ||
| 55 | cout << value << endl; | ||
| 56 | } | ||
| 57 | |||
| 58 | int | ||
| 59 | main() | ||
| 60 | { | ||
| 61 | part1(); | ||
| 62 | } | ||
