Day 1: Dusty Shed
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


C++
As I’ve started learning C++, I will be doing the easier puzzles in C++ as well as my usual Kotlin. This is definitely still beginner code and less fancy than the other solution in this thread, but hey it works.
If you see any possible improvements do let me know!
Solution
static std::vector<int> read_file(const std::string_view path) { const fs::path file{path}; std::ifstream in{file}; if (!in) { std::cerr << "cannot read " << file << '\n'; return {}; } std::vector<int> out; int number; while (in >> number) { out.push_back(number); } if (!in.eof()) { std::cerr << "invalid input or read error in " << file << '\n'; } return out; } static std::unordered_map<int, long> get_counts(const std::vector<int>& numbers) { std::unordered_map<int, long> map; for (const int number : numbers) { ++map[number]; } return map; } static long part_1(const std::vector<std::pair<int, long>>& counts) { long prod{1}; for (std::size_t i{0}; i < 3; ++i) { prod *= counts[i].first; } return prod; } static long part_2(const std::vector<std::pair<int, long>>& counts) { const std::size_t len{std::size(counts)}; long prod{1}; for (std::size_t i{len - 1}; i > len - 4; --i) { prod *= counts[i].first; } return prod; } int main() { const std::vector nums{read_file("/home/eco/code/aoc_cpp/res/day01.txt")}; const std::unordered_map counts{get_counts(nums)}; const auto comp = [](const std::pair<int, long>& a, const std::pair<int, long>& b) { return a.second > b.second; }; std::vector<std::pair<int, long>> counts_vector; counts_vector.assign(counts.begin(), counts.end()); std::sort(counts_vector.begin(), counts_vector.end(), comp); std::cout << "part 1: " << part_1(counts_vector) << '\n'; std::cout << "part 2: " << part_2(counts_vector) << '\n'; return 0; }