|
| 1 | +#include <rusty_iterators/file_iterator.hpp> |
| 2 | +#include <rusty_iterators/iterator.hpp> |
| 3 | + |
| 4 | +#include <cassert> |
| 5 | +#include <iostream> |
| 6 | +#include <sstream> |
| 7 | +#include <string> |
| 8 | + |
| 9 | +using ::rusty_iterators::iterator::FileIterator; |
| 10 | +using ::rusty_iterators::iterator::FIterType; |
| 11 | +using ::rusty_iterators::iterator::LazyIterator; |
| 12 | + |
| 13 | +auto splitByWhitespaceAndCastToInt(std::string str) -> std::vector<int> |
| 14 | +{ |
| 15 | + std::istringstream iss{str}; |
| 16 | + std::vector<int> tokens{}; |
| 17 | + std::string token; |
| 18 | + |
| 19 | + while (std::getline(iss, token, ' ')) |
| 20 | + { |
| 21 | + if (!token.empty()) |
| 22 | + tokens.push_back(std::atoi(token.c_str())); |
| 23 | + } |
| 24 | + return std::move(tokens); |
| 25 | +} |
| 26 | + |
| 27 | +auto isReportSafe(std::vector<int> vec) -> bool |
| 28 | +{ |
| 29 | + auto signum = (vec.at(1) - vec.at(0)) > 0 ? 1 : -1; |
| 30 | + |
| 31 | + return LazyIterator{vec}.movingWindow(2).all([&signum](auto x) { |
| 32 | + auto result = x.at(1) - x.at(0); |
| 33 | + auto currSignum = result > 0 ? 1 : -1; |
| 34 | + auto absResult = std::abs(result); |
| 35 | + |
| 36 | + return absResult >= 1 && absResult <= 3 && currSignum == signum; |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +/* |
| 41 | + * An example solution to Advent of Code 2024: day 2, part 1. |
| 42 | + * https://adventofcode.com/2024/day/2 |
| 43 | + */ |
| 44 | +auto main() -> int |
| 45 | +{ |
| 46 | + auto result = FileIterator<FIterType::Lazy>{std::string{"./examples/aoc/input.txt"}} |
| 47 | + .map(splitByWhitespaceAndCastToInt) |
| 48 | + .filter(isReportSafe) |
| 49 | + .count(); |
| 50 | + |
| 51 | + std::cout << "Expected amount of safe reports: 2" << std::endl; |
| 52 | + std::cout << "Calculated amount of safe reports: " << result << std::endl; |
| 53 | + |
| 54 | + assert(result == 2); |
| 55 | +} |
0 commit comments