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/[deleted] Dec 02 '18

C-Sharp

I'm really not happy with my solutions, but hey, they get the work done.

First part, I use two lists and two bools to to calculate the checksum. This looks just... very bad. Oh well.

public int GetChecksum()
{
	var lOfTwo = new List<char>();
	var lOfThree = new List<char>();

	using (var sr = new StreamReader("input2.txt")) {
		while (sr.Peek() > -1) {
			var line = sr.ReadLine().ToCharArray();
			var groups = line.GroupBy(item => item);

			//Count every occurence of 2's or 3's only once
			var addedTwo = false;
			var addedThree = false;
			foreach (var g in groups) {
				if (g.Count() == 2 && !addedTwo) {
					lOfTwo.Add(g.Key);
					addedTwo = true;
				}
				if (g.Count() == 3 && !addedThree) {
					lOfThree.Add(g.Key);
					addedThree = true;
				}
			}
		}
	}

	var checkSum = lOfTwo.Count * lOfThree.Count;
	return checkSum;
}

But wait, it gets even worse! Using a foreach inside two for-loops to check the differences. And to top it all off, I use a goto when the solution is found. Wow.

public string GetID()
{
	var checkSumList = new List<string>();
	using (var sr = new StreamReader("input2.txt")) {
		while (sr.Peek() > -1)
			checkSumList.Add(sr.ReadLine());
	}

	var diff = 0;
	var id1 = "";
	var id2 = "";
	for (int i = 0; i < checkSumList.Count(); i++) {
		for (int j = i + 1; j < checkSumList.Count(); j++) {
			var counter = 0;
			foreach (var c in checkSumList[i]) {
				if (c.Equals(checkSumList[j][counter]) == false) {
					if (++diff > 1)
						break;
				}
				counter++;
			}

			if (diff > 1) {
				diff = 0;
				continue;
			}

			//We have a result!
			id1 = checkSumList[i];
			id2 = checkSumList[j];
			goto end;
		}
	}

end:
	//remove differing char from ID
	var count = 0;
	var sb = new StringBuilder();

	foreach(var c in id1) {
		if(c.Equals(id2[count++]))
			sb.Append(c);
	}

	return sb.ToString();
}