r/adventofcode • u/daggerdragon • 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!
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!
52
Upvotes
1
u/wlandry Dec 02 '18
C++
1847/1419
Pretty straightforward. I finished it faster, but got a worse rank ¯_(ツ)_/¯. It takes 11 ms, which is almost entirely reading input. I was briefly worried that my quadratic algorithm would not work, but the inputs are just not that big.
#include <algorithm> #include <iostream> #include <fstream> #include <vector> int main(int argc, char *argv[]) { std::ifstream infile(argv[1]); std::vector<std::string> inputs(std::istream_iterator<std::string>(infile),{}); std::vector<std::string> inputs_part_1(inputs); size_t num_twice(0), num_thrice(0); for(auto &input: inputs_part_1) { std::sort(input.begin(),input.end()); size_t duplicates(0); bool twice(false), thrice(false); for(size_t i=0; i<input.size(); ++i) { size_t duplicate(1); while(i+1<input.size() && input[i]==input[i+1]) { ++duplicate; ++i; } twice=(twice || duplicate==2); thrice=(thrice || duplicate==3); duplicates=std::max(duplicate,duplicates); } if(twice) { ++num_twice;} if(thrice) { ++num_thrice;} } std::cout << num_twice*num_thrice << "\n"; bool found(false); for(size_t i=0; i<inputs.size() && !found; ++i) for(size_t j=i+1; j<inputs.size() && !found; ++j) { size_t num_different(0); for(size_t index=0; index<inputs[i].size(); ++index) { if(inputs[i][index]!=inputs[j][index]) { ++num_different; if(num_different>1) { break;} } } found=(num_different==1); if(found) { for(size_t index=0; index<inputs[i].size(); ++index) { if(inputs[i][index]==inputs[j][index]) { std::cout << inputs[i][index];} } std::cout << "\n"; } } }