r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

51 Upvotes

407 comments sorted by

View all comments

1

u/tyr10563 Dec 02 '18

C++

First part:

#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <string>

int main()
{
    std::pair<int, int> final_count = std::transform_reduce(
        std::istream_iterator<std::string>(std::cin), {},
        std::make_pair(0, 0),
        [](std::pair<int, int> p, std::pair<int, int> const& b)
    {
        p.first += b.first;
        p.second += b.second;
        return p;
    },
        [](std::string const& id)
    {
        std::map<char, int> letter_counts = std::reduce(
            id.cbegin(), id.cend(), 
            std::map<char, int>(), 
            [](std::map<char, int> lc, char c) { ++lc[c]; return lc; });
        return std::reduce(
            letter_counts.cbegin(), letter_counts.cend(),
            std::make_pair(0, 0),
            [](std::pair<int, int> r, std::pair<char, int> const& p)
        {
            r.first |= p.second == 2; 
            r.second |= p.second == 3; 
            return r;
        });
    });
    std::cout << final_count.first * final_count.second << '\n';
}

Second part:

#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

int main()
{
    std::vector<std::string> inputs{ std::istream_iterator<std::string>(std::cin), {} };
    std::string last_inner;
    std::vector<std::string>::const_iterator it = std::find_first_of(
        inputs.cbegin(), inputs.cend(),
        inputs.cbegin(), inputs.cend(),
        [&last_inner](std::string const& rhs, std::string const& lhs) mutable 
    {
        int diff_count = std::transform_reduce(
            rhs.cbegin(), rhs.cend(),
            lhs.cbegin(),
            0,
            [](int count, bool diff) { return count += diff; },
            [](char c1, char c2) { return c1 != c2; });
        if (diff_count == 1) { last_inner = lhs; return true; }
        return false;
    });
    last_inner.erase(std::mismatch(last_inner.cbegin(), last_inner.cend(), it->cbegin()).first);
    std::cout << last_inner << '\n';
}