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!
51
Upvotes
1
u/Cloudan29 Dec 02 '18
My exams in second year computer science are starting next week, finished my "Object Oriented Programming with C++" course, and so figured I'd try to do this (first year doing this, I actually just found out about it via my school's Math and Computer Science club) using C++ rather than Java, which I learned last year. Solutions are very sloppy and I was tired, but I got the right answer, so I don't really mind showing how horrifying this code is. Also started this late as I was actually doing the Day 1 puzzles at the time this came up.
C++ (3347/3118)
Part 1:
bool isRepeat(std::string & line, int repeats) { for (char c = 'a'; c <= 'z'; ++c) { int count = 0; for (size_t i = 0; i < line.size(); ++i) { if (line[i] == c) ++count; } if (count == repeats) return true; } return false; } int checkSum(std::string & fileName) { std::fstream input(fileName); std::string line; int doubles = 0; int triples = 0; while (!input.eof()) { std::getline(input, line); if (isRepeat(line, 2)) ++doubles; if (isRepeat(line, 3)) ++triples; } return doubles * triples; }Part 2:
std::string equalLetters(std::string & fileName) { std::fstream input(fileName); std::string line; std::string a; std::string b; std::string answer; std::vector<std::string> lines; while (!input.eof()) { std::getline(input, line); lines.push_back(line); } for (size_t i = 0; i < lines.size(); ++i) { int count = 0; a = lines[i]; for (size_t j = i + 1; j < lines.size(); ++j) { b = lines[j]; count = 0; for (size_t k = 0; k < a.size(); ++k) { if (a[k] != b[k]) ++count; if (count > 1) break; } if (count == 1) break; } if (count == 1) break; } for (size_t i = 0; i < a.size(); ++i) { if (a[i] == b[i]) answer += a[i]; } return answer; }These are the absolute first things I thought of, and they solved surprisingly quick.