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!

53 Upvotes

407 comments sorted by

View all comments

Show parent comment

1

u/hpzr24w Dec 02 '18

Improved part 2 even further. See this talk by Marshall Clow, which describes adding a for_all_pairs algorithm to the STL. https://youtu.be/h4Jl1fk3MkQ?t=1420

// Advent of Code 2018
// Day 02 - Inventory Management System

#include "../aoc.hpp"
using namespace std;

int main(int argc, char* argv[]) {
    auto input = vector<string>(read_input("day_02.txt"));

    // Part 1 - Compute a checksum from multiplying counts of words with letters occurring exactly 2 or 3 times
    auto twos{0}, threes{0};
    for_each(begin(input),end(input),[&](auto& w) { 
        any_of(begin(w),end(w),[&](auto& c)->bool {return count(begin(w),end(w),c)==2;}) && twos++;
        any_of(begin(w),end(w),[&](auto& c)->bool {return count(begin(w),end(w),c)==3;}) && threes++;
    });
    cout << "Part 1: Checksum: " << twos*threes << "\n";

    // Part 2 - find the two strings that differ by only a single letter
    for_all_pairs(begin(input),end(input),[&](auto& w1, auto& w2) {
        auto found = bool(count_mismatches(begin(w1),end(w1),begin(w2))==1);
        found && cout << "Part 2: Single letter diff: "<< w1 << " " << w2 << "\n";
    });
}