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

Show parent comment

2

u/Nathan340 Dec 02 '18

Part 1

Knew off the bat that grouping would be the key here. Got somewhat lost in which column I was checking, and also ran into some ambiguity of trying to access the column called count versus the count property of an array.

But basically split each string by the empty character, ditch the weird blanks that show up, group, group by count, and then look for 2 or 3 in the name column. Multiply the two results together.

$in = gc .\2-input.txt
$twos = $in | ? {
	$_ -split "" | ?{$_} | group | group count | ? {2 -in $_.name}
}
$threes = $in | ? {
	$_ -split "" | ?{$_} | group | group count | ? {3 -in $_.name}
}

$twos.length * $threes.length

Part 2

Already outside of leader-board contention, and from my data structure lesson on day one, I first did some research. I found that ArrayList has a removeAt function to drop an element from a specific index.

So for each index 0 to 25, create the list of the 250 input words with that index dropped. At each pass check if you have a duplicate (grouping is on the brain for this one, but maybe the Day 1 duplicate checking via hash table would have worked better). If the duplicate is found, print it and break the loop early.

0..25 | % {
	$curDropIndex = $_
	$droppedList = $in | % {
		$curWord = new-object system.collections.arraylist(,($_ -split "" | ?{$_}))
		$curWord.removeAt($curDropIndex)
		$curWord -join ""
	}
	$dupe = $droppedList | group | ?{$_.count -ne 1} | select -expandproperty name
	if($dupe){
		write-host $dupe
		break
	}
}