aoc24: day01 complete

This commit is contained in:
2024-12-02 00:20:45 +01:00
parent f83428ded9
commit 04e64612b9

63
aoc.cpp
View File

@@ -1,10 +1,71 @@
#include <fstream> #include <fstream>
#include <vector> #include <vector>
#include <algorithm>
#include <ranges>
#include <numeric>
#include <cmath>
#include <utility>
#include "fmt/format.h" #include "fmt/format.h"
#include "aoc/24/01.hpp"
auto main([[maybe_unused]]int argc, [[maybe_unused]]char const* argv[]) -> int { auto main([[maybe_unused]]int argc, [[maybe_unused]]char const* argv[]) -> int {
std::fstream strm{"./data/2024/day01/sample.txt", std::ios::in}; constexpr auto filename = "./dat/24/re/01.txt";
std::ifstream strm{filename, std::ios::in};
if (!strm.is_open()) {
fmt::print("Error opening file: {}\n", filename);
return 1;
}
std::vector<std::uint32_t> a{};
std::vector<std::uint32_t> b{};
std::string str{};
while (strm) {
auto const c = char(strm.peek());
if (std::isdigit(c)) {
str += char(strm.get());
continue;
}
if (c == ' ') {
if (!str.empty()) {
a.emplace_back(std::stoi(str));
str.clear();
}
}
if (c == '\n') {
if (!str.empty()) {
b.emplace_back(std::stoi(str));
str.clear();
}
}
[[discard]]strm.get();
}
fmt::print("a: {}, b: {}\n", a.size(), b.size());
std::sort(std::begin(a), std::end(a));
std::sort(std::begin(b), std::end(b));
auto diff_view = std::views::zip_transform([](auto a, auto b) {
return a > b ? a - b : b - a;
}, a, b);
auto const sum = std::accumulate(std::begin(diff_view), std::end(diff_view), 0);
fmt::print("Part A: {}\n", std::abs(sum));
auto values = a | std::views::transform([&b](auto v) {
return std::pair{v, b | std::views::filter([v](auto c) {
return v == c; // Filter elements in `b` equal to `v`
}) | std::ranges::to<std::vector>()};
}) | std::ranges::to<std::vector>();
auto const meow = std::accumulate(std::begin(values), std::end(values), 0, [](auto const acc, auto const& pair) {
return acc + std::int32_t(pair.first * pair.second.size());
});
fmt::print("Part B: {}\n", meow);
return 0; return 0;
} }