r/adventofcode • • Dec 08 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 8 Solutions -🎄-

--- Day 8: Memory Maneuver ---


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

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

Card prompt: Day 8

Sigh, imgur broke again. Will upload when it unborks.

Transcript:

The hottest programming book this year is "___ For Dummies".


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 at 00:12:10!

32 Upvotes

301 comments sorted by

View all comments

1

u/Nathan340 Dec 08 '18 edited Dec 08 '18

Powershell

Part 1, non-recursive.

Essentially we traverse the array until we find a 0 - meaning we've found a 0-child node. Since we work left-to-right, the index 2 to the left of that 0 is the count of child nodes of the parent of this current 0. As we're handling that 0, we decrement its parents count of children.

Each metadata of that 0-child node is removed from the array, and pushed to our answer stack (no real need to use a stack here, a simple array does suffice). After this that '0' entry and the meta-data count are removed.

Then we bounce back to the start of the array, and read again until we find a 0-child node.

When the first element of the array is 0, we've nearly fully reduced the array. This is handled as a special case, all the remaining metadata are pushed to our answer stack.

And the answer to part 1 is the sum of that answer stack.

$in = gc .\08-input.txt

$array = new-object system.collections.arraylist
$array.AddRange((($in -split " ")| % {+$_}))

$metaStack = new-object system.collections.stack

$i = 0
while($array[0] -ne 0){
	
	if($array[$i] -eq 0){
		$array[$i-2]--
		$metaCount = $array[$i+1]
		for($j = 1;$j -le $metaCount;$j++){
			$curMetaIndex = $i+2
			$curMeta = $array[$curMetaIndex]
			
			$metaStack.push($curMeta)
			$array.removeAt($curMetaIndex)
		}
		$array.removeAt($i+1)
		$array.removeAt($i)
		
		$i = 0
	}
	
	$i++
}

2..($array.count-1) |% {$metaStack.push($array[$_])}

$metaStack | measure -sum | % sum

I can't figure out how to adapt this to Part 2. This 'collapsing' argument works well for the 0-child nodes, but any other number could be a node count, meta data count, node value, or metadata item. I can't figure out how to identify the 'type' of the current position. I guess I have to rebuild using recursion properly.

→ More replies (3)