r/adventofcode • • Dec 03 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 3 Solutions -🎄-

--- Day 3: No Matter How You Slice It ---


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

ATTENTION: minor change request from the mods!

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 3 image coming soon - imgur is being a dick, so I've contacted their support.

Transcript:

I'm ready for today's puzzle because I have the Savvy Programmer's Guide to ___.


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!

41 Upvotes

426 comments sorted by

View all comments

1

u/JulianLoehr Dec 03 '18

C++

I don't traverse the input nor the array a second time.

constexpr size_t ClothSize = 1000;
typedef std::array<std::pair<size_t, size_t>, ClothSize * ClothSize> ClothArray;
typedef std::shared_ptr<ClothArray> ClothArrayPtr;

int main()
{
	ClothArrayPtr Cloth = std::make_shared<ClothArray>();
	std::regex InputMatching("#(\\d+)\\s@\\s(\\d+),(\\d+):\\s(\\d+)x(\\d+)");
	StringVector File = GetFileLines("Input.txt");
	size_t OverlappingSquares = 0;
	std::unordered_set<size_t> NonOverlappingIDs;

	for (const std::string & Line : File)
	{
		std::smatch Matches;
		if (!std::regex_match(Line, Matches, InputMatching))
		{
			std::cout << "Line \"" << Line << "\" did not match the regex!" << std::endl;
			return 1;
		}

		bool IsNonOverlapping = true;
		size_t ID = std::stoull(Matches[1]);
		size_t XStart = std::stoull(Matches[2]);
		size_t YStart = std::stoull(Matches[3]);
		size_t Width = std::stoull(Matches[4]);
		size_t Height = std::stoull(Matches[5]);

		for (size_t X = XStart; X < (XStart + Width); ++X)
			for (size_t Y = YStart; Y < (YStart + Height); ++Y)
			{
				auto & Field = (*Cloth)[Y * ClothSize + X];

				if (Field.first == 1)
					++OverlappingSquares;

				if (Field.first != 0)
				{
					NonOverlappingIDs.erase(Field.second);
					IsNonOverlapping = false;
				}

				++Field.first;
				Field.second = ID;
			}

		if (IsNonOverlapping)
			NonOverlappingIDs.insert(ID);
	}

	std::cout << "Part One: " << OverlappingSquares << std::endl;
	std::cout << "Part One: " << *NonOverlappingIDs.begin() << std::endl;
}